关于多线程中this的小问题

ch4m0n1x 2010-05-30 03:47:15
class NewThread implements Runnable{
Thread t;

NewThread(){
t = new Thread(this,"Demo Thread");//想请教下这个this的作用,指向的是哪个对象,请高手帮帮忙,谢谢啦
System.out.println("Child thread: " + t);
t.start();
}
public void run(){
try{
for(int i=5;i>0;i--){
System.out.println("child thread: " + i);
Thread.sleep(500);
}
}catch(InterruptedException e){
System.out.println("child interrupted.");
}
System.out.println("Exiting child thread.");
}
}

class ThreadDemo{
public static void main(String args[]){
new NewThread();

try{
for(int i=5;i>0;i--){
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
}catch(InterruptedException e ){
System.out.println("main thread interrupted.");
}
System.out.println("main thread exiting.");
}
}
...全文
147 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
izard999 2010-05-30
  • 打赏
  • 举报
回复
this是指代当前这个内部类的对象, 外部类的this要用外部类名.this
zqfddqr 2010-05-30
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 rumlee 的回复:]

在任何地方使用this都是指向当前对象。

作用是为线程指定父线程。
[/Quote]
uqortbsa 2010-05-30
  • 打赏
  • 举报
回复
就是指当前对象
rumlee 2010-05-30
  • 打赏
  • 举报
回复
在任何地方使用this都是指向当前对象。

作用是为线程指定父线程。
xiaowei_8868 2010-05-30
  • 打赏
  • 举报
回复
指的是NewThread实例对象本身,类的构造方法中的this指的是该类实例化对象本身
和如下调用结果相同:

NewThread t=new NewThread();
Thread th=new Thread(t);
th.start();
//////////////////
Thread th=new Thread(new NewThread());
th.start();


62,620

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧