[英]Multithreaded Programming In Java
我正在学习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
甚至没有运行!
“ 此 ”:-
此关键字可用于引用当前的类实例变量。
this()可用于调用当前类的构造函数。
此关键字可用于(隐式)调用当前的类方法。
这可以作为方法调用中的参数传递。
这可以在构造函数调用中作为参数传递。
此关键字还可以用于返回当前的类实例。
这里的“这”是指线程/可运行对象。 由于Demo类是继承的,因此Runnable Interface Demo类可以视为线程。 因此,解析关键字“ this”指的是当前对象,当我们调用“ t.start()”时,它将在新线程中执行run()方法。 当然,您也可以解析新的演示对象,但可以使用其他构造函数创建该对象,因为否则,当我们创建演示对象时,它将在循环中调用构造函数。
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构造函数时,将通过“ Child-2”线程调用名为“ Constructor-2”的线程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.