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