为什么将“this”传递给Thread构造函数?

时间:2012-03-01 11:31:39

标签: java multithreading

“this”用于指代当前类的成员。我正在使用多线程在java中尝试一个程序。

this =>引用它的当前类的对象

该计划

class Thread_child implements Runnable{
    Thread t;

    Thread_child()
    {
        t = new Thread(this,"DemoThread");
        System.out.println("ChildThread:"+t);
        t.start();
    }
    public void run(){
    char a[] = {'A','B','C','D','E','F','G','H','I','J'};
    try{
        for(int i=0;i<10;i++){
            System.out.println("ChildThread:"+i+"\t char :"+a[i]);
            Thread.sleep(5000);
        }
     }
     catch(InterruptedException e){
        System.out.println("ChildThread Interrupted");
     }
      System.out.println("Exiting from the Child Thread!");
    }
}
class Thread_eg{

    public static void main(String args[]){
        new Thread_child();
        try{
            for(int i=1;i<=10;i++){
            System.out.println("MainThread:"+i);
            Thread.sleep(3000);
        }
        }
        catch(InterruptedException e){
            System.out.println("MainThread Interrupted");
        }
        System.out.println("Exiting from the Main Thread!");

    }

}

这个Thread()构造函数做了什么。为什么我们需要将'this'作为参数传递给它。我尝试在不给出参数的情况下运行它,但子线程没有运行。只打印了mainthread。当我用参数替换线程构造函数时,它运行子线程。为什么会这样?

3 个答案:

答案 0 :(得分:3)

查看该构造函数的documentation,一切都应该清楚。特别注意陈述

的部分
  

如果target参数不是null,则在启动此线程时会调用run的{​​{1}}方法。如果目标参数为target,则在启动此线程时将调用此线程的null方法。

(潜在的问题是,一个线程只是一个线程,并且本身并没有做任何事情。你需要告诉它要执行什么。)

答案 1 :(得分:3)

因为thisRunnable对象(Thread_child),run()方法被调用。

答案 2 :(得分:0)

实现Thread有两种方法。一个是创建一个extends Thread类的类,这个类作为VM中的一个线程运行。

MyThread mt = new MyThread();
mt.start();

开始将导致执行从run覆盖的Thread方法。

如果您无法扩展到Thread,则可以实施Runnable,这会让您实施run方法。现在要运行此类,您需要将其对象传递给Thread

MyRunnable mr = new MyRunnable();
Thread t = new Thread(mr); // telling the thread what needs to be execute through run method
t.start();

在您的代码中,因为您在构造函数中启动了线程,所以在上面的示例中,您已经通过了this而不是mr。基本上,您需要通过Thread方法告诉run它需要做什么。

这就是Thread的run的样子:

public void run() {
if (target != null) { //target is nothing but a Runnable.
    target.run(); 
}
}