在“this”对象和构造函数中的CurrentThread之间

时间:2014-01-22 19:26:51

标签: java multithreading

在进行多线程练习时,我发现我无法在代码中设置线程的名称。我可以使用this来引用当前对象,然后在构造线程以访问当前线程时我不能使用Thread.currentThread。我有点困惑。请帮帮我。

什么时候实际创建线程?是在构造线程实例时还是在线程上调用方法start()时?

currentThread在这里意味着什么?

public class RecursiveRunnableTest {

    public static void main(String... args){
        Thread t =  new Thread(new RecursiveRunnable("First thread"));
        t.start();
    }


}

class RecursiveRunnable implements Runnable {

    private String name;
    public RecursiveRunnable(String name) {
        this.name = name;
        Thread.currentThread().setName(this.name); // Expecting to set the name of thread here
    }
    @Override
    public synchronized void run() {
        System.out.println(Thread.currentThread().getName()); // displaying Thread-0
        System.out.println(this.name); // displaying "First thread"

        try{
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally{

        }
    }
}

2 个答案:

答案 0 :(得分:2)

仅仅因为主线程构造它而不是t线程构造自己。所以,你可以重写这个(在开始之前设置线程的名称):

public class RecursiveRunnableTest {

    public static void main(String... args){
        RecursiveRunnable rr = new RecursiveRunnable("First thread");
        Thread t =  new Thread(rr);
        t.setName(rr.getName());
        t.start();
    }


}

class RecursiveRunnable implements Runnable{

    private String name;
    public RecursiveRunnable(String name) {
        this.name = name;
    }
    public String getName(){return this.name;}
    @Override
    public synchronized void run() {
        System.out.println(Thread.currentThread().getName()); // displaying Thread-0
        System.out.println(this.name); // displaying "First thread"

        try{
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally{

        }
    }
}

答案 1 :(得分:1)

尝试这样做

Thread t = new Thread(new RecursiveRunnable("First thread"));
t.start();
Thread.sleep(1L);
System.out.println("main thread: " + Thread.currentThread().getName()); // same thread that created the RecrusiveRunnable instance

你会看到

main thread: First thread 

打印。 这是因为主线程构建了RecursiveRunnable,所以

Thread.currentThread().setName(this.name); 

实际上是在改变主线程的名称,而不是Runnable最终将运行的线程。


另外

System.out.println(this.name); // displaying "First thread"

指的是name对象的RecursiveRunnable字段,您将其设置为与主线程相同的值。