class TwoThread implements Runnable{ TwoThread(){ Thread t1=Thread.currentThread(); t1.setName("The first main thread"); System.out.println("The running thead:"+t1); Thread t2=new Thread(this,"the second thread");//注重这里的this,它表明新线程即t2将会做的事情由this对象来决定,也就是由twothread的run函数来决定 System.out.println("create another thread"); t2.start();//调用该函数将使线程从run函数开始执行 try{ System.out.println("first thread will sleep"); Thread.sleep(3000); }catch(InterruptedException e){System.out.println("first thread has wrong");} System.out.println("first thread exit"); }
public void run()//定义run()函数,在本程序中也就是t2这个新的线程会做的事情 { try{ for(int i=0;i<5;i++) { System.out.println("sleep time for thread 2:"+i); Thread.sleep(1000); } }catch(InterruptedException e){System.out.println("thread has wrong");} System.out.println("second thread exit"); } public static void main(String args[]){ new TwoThread();//触发构造函数 } }
运行的结果如下: The running rhread:Thread[The first main thread,5,main] creat another thread first thread will sleep Sleep time for thread 2:0 Sleep time for thread 2:1 Sleep time for thread 2:2 first thread exit Sleep time for thread 2:3 Sleep time for thread 2:4 second thread exit