关于this
我在学习中,下面这个程序是看的书上的,原来主线程是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.");
}
}
------解决方案--------------------你的子线程 不是守护线程,不会因为 main的退出,而结束。
this 就是指的这个线程并且实现了runnable接口