关于this

机器学习之禅 2014-03-12 05:04:15
我在学习中,下面这个程序是看的书上的,原来主线程是sleep(1000)
我尝试把主线程改成sleep(10)
输出的显示表明主线程先结束了,但是子线程还在运行,这是怎么回事?
子线程可以在没有主线程的情况下独立运行吗?
另外我想问问谁解释下载 newThread 构造函数中的this这句什么意思
//create a new thread
class newThread implements Runnable{
Thread t;//clarify the instance of new thread

newThread(){//construct function initialize
t = new Thread(this, "Demo Thread");//point the current thread and set its name
System.out.println("Child thread:" + t);
t.start();//start the new thread
}
//为实现Runnable 接口,一个类仅需实现一个run()的简单方法 public void run( )
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 thread interrupted!" );
}
System.out.println("Exit Child thread.");
}
}
public class ThreadDemo {

public static void main(String[] args) {
// TODO Auto-generated method stub
new newThread();
try {
for(int i = 5; i > 0; i--) {
//new newThread();
System.out.println("Main Thread: " + i);
Thread.sleep(10);
}
} catch (InterruptedException e){

System.out.println("Main thread interrupted.");
}
System.out.println("Exit main thread.");
}

}
...全文
86 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
你的子线程 不是守护线程,不会因为 main的退出,而结束。 this 就是指的这个线程并且实现了runnable接口

67,513

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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