带有runnable参数的线程打印名称

时间:2018-06-11 08:03:47

标签: java

嗨,伙计们,我正在努力学习java多线程的基础知识,在学习的过程中我找到了这个练习

public class Test {

    public static void main(String[] args) {
        Runnable rrr = () -> Thread.currentThread().setName(args[0]);
        new print(rrr).start();
    }
}

练习要求实现打印类,以便以下测试打印args [0]的值

 public class print extends Thread{

     public print(Runnable rrr) {
     }

     public void run()
     {
          System.out.println("run() called by " +      Thread.currentThread().getName());
          System.out.println(Thread.currentThread().getName());
     }
 }

这是我的实施,是吧?

2 个答案:

答案 0 :(得分:1)

Runnable rrr参数未使用。所以代码不会在任何地方执行。您需要将代码更改为

 public class print extends Thread{

     private Runnable rrr;
     public print(Runnable rrr) {
         this.rrr = rrr;
     }

     public void run()
     {
          rrr.run(); // this runs "Thread.currentThread().setName(args[0])"
          System.out.println("run() called by " +      Thread.currentThread().getName());
          System.out.println(Thread.currentThread().getName());

     }
 }

让它发挥作用。

更简单的方法:

Thread t = new Thread(() -> {
    System.out.println("Thread name is " + Thread.currentThread().getName());
});
t.setName("Peter");
t.start();
  

线程名称是Peter

答案 1 :(得分:0)

当线程启动它时,不需要Runnable直接调用run方法