thread(this, ThreadName)对于Java中这个语句,this是什么?还有Thread为什么需要一个this?

新手上路,请多包涵

就拿这个程序为例。
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");
}
}

阅读 9.2k
3 个回答

首先,这是一个构造函数,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,所以就这么写了。

新手上路,请多包涵

this 可以代表任何对象,当 this 出现在某个方法体中时,它所代表的对象是不确定的,但它的类型是确定的,它所代表的只能是当前类的实例。只有当这个方法被调用时,它所代表的对象才被确定下来,谁在调用这个方法,this 就代表谁。
实现接口的对象实例是你后来创建的,而this感觉就像先占个位置一样。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题