我正在学习Java中的多线程概念,并且遇到了一个通过实现runnable类来创建新线程的程序。以下是我怀疑的代码的一部分:
class Demo implements Runnable
{
Thread t;
Demo()
{
t=new Thread(this,"child_thread1");
System.out.println("Thread Info:"+t);
t.start();
}
}
现在,有人可以向我解释一下this
的用途吗?我尝试传递this
类的对象,而不是传递Demo
。事实证明,child_thread1
甚至没有运行!
答案 0 :(得分:0)
“this”: -
此关键字可用于引用当前的类实例变量。
this()可用于调用当前的类构造函数。
此关键字可用于调用当前类方法(隐式)。
这可以作为方法调用中的参数传递。
这可以在构造函数调用中作为参数传递。
此关键字也可用于返回当前的类实例。
答案 1 :(得分:0)
这里'this'表示Thread / Runnable的对象。由于Demo Class是继承的,Runnable Interface Demo类可以被视为一个线程。所以解析关键字'this'引用当前对象,当我们调用't.start()'时它在新线程中执行run()方法。当然,您也可以解析新的Demo Object,但是使用不同的构造函数创建该对象,否则当我们创建Demo对象时,它将在循环中调用构造函数。这是一个示例
public class Demo implements Runnable{
Thread t1,t2;
public Demo(){
//Create Child 1 with First constructor
t1=new Thread(new Demo(true),"Child-1");
System.out.println("Thread Info:"+t1);
t1.start();
//Create Child 2 with Second constructor
t2=new Thread(new Demo(1),"Child-2");
System.out.println("Thread Info:"+t2);
t2.start();
}
public Demo(boolean b){
t1=new Thread();
t2=new Thread();
}
public Demo(int i){
t1=new Thread("Constructor 2"){
@Override
public void run() {
System.out.println("Internal Thread "+Thread.currentThread().getName());
}
};
t1.start();
}
@Override
public void run() {
//Work goes Here/
System.out.println("Thread Works :"+Thread.currentThread().getName());
}
/**/
public static void main(String[] args) {
//Default Constructor
Demo demo=new Demo();
}
}
这里当我们调用Second构造函数时,'Constructor-2'命名的线程是通过'Child-2'线程调用的。