this的用法 - thread(this, ThreadName)对于Java中这个语句,this是什么?还有Thread为什么需要一个this?
黄舟
黄舟 2017-04-17 11:41:17
0
2
1001

就拿这个程序为例。
public class GetCurrentThread implements Runnable {
Thread th;

public GetCurrentThread(String threadName) {
th = new Thread(this,threadName); //<----DOUBT
System.out.println("get threadname "+th.getName());
th.start();
}

public void run() {
System.out.println(th.getName()+" is starting.....");
System.out.println("Current thread name : " + Thread.currentThread().getName());
}

public static void main(String args[]) {
System.out.println("Current thread name : " + Thread.currentThread().getName());
new GetCurrentThread("1st Thread");
//new GetCurrentThread("2nd Thread");
}
}

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

Antworte allen(2)
巴扎黑

首先,这是一个构造函数,SDK说明如下

public Thread(Runnable target,
String name)
Allocates a new Thread object. This constructor has the same effect as Thread (null, target, name).
Parameters:
target - the object whose run method is invoked when this thread is started. If null, this thread's run method is invoked.
name - the name of the new thread

两个参数Runnable和String类型,你的GetCurrentThread实现了Runnable接口,这里的this是代表当前对象,恰好这里的当前对象是一个Runnable。

黄舟

Thread要的不是this,它要一个Runnable,在你的代码里,刚好this是一个Runnable,所以就这么写了。

Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage