public class thread1 {
public static void main(String args[]){
new NewThread(); //creat a new thread
try{
for(int i=5;i>0;i--)
{
System.out.println("main Thread:"+i);
Thread.sleep(1000);
}
}
catch(InterruptedException e){
System.out.print("main threa interrupted.");
}
System.out.print("main threa exiting.");
}
}
class NewThread implements Runnable{
Thread t;
NewThread(){
t=new Thread(this,"Demo Thread:"+t);
System.out.println("chind thread:"+t);
t.start(); //start the thread
}
//@Override
public void run() {
// TODO Auto-generated method stub
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 interrupted.");
}
}
其中,语句this表明在this对象中要用新的线程调用run()方法,然后再调用start()方法。接着run()方法开始执行线程,这时子线程的for循环开始执行,调用start()方法后,NewThread的构造函数返回到main()方法。当主线程被恢复时,它到达for循环。两个线程会继续运行,并共享CPU,直到它们的循环结束。
运行结果如下:
chind thread:Thread[Demo Thread:null,5,main]
child thread:5
main Thread:5
child thread:4
main Thread:4
child thread:3
child thread:2
main Thread:3
child thread:1
Exiting child interrupted.
main Thread:2
main Thread:1
main threa exiting.