多執行緒學習(三):isAlive()和sleep()和getId()
阿新 • • 發佈:2019-01-07
isAlive()
isAlive()判斷執行緒是否處於活動狀態,即執行緒已經啟動但尚未終止。
例一
public class MyThread extends Thread{ @Override public void run() { System.out.println("run="+this.isAlive()); } public static void main(String[] args) throws InterruptedException { MyThread myThread = new MyThread(); System.out.println("myThread還未執行,所以結果是false:"+myThread.isAlive()); myThread.start(); //物件自我排程,所以this.isAlive()是存活的 Thread.sleep(1000); System.out.println("myThread應該執行結束,所以結果是true:"+myThread.isAlive()); } }
執行結果
例二
public class MyThread02 extends Thread{ //構造方法 public MyThread02() { System.out.println("構造方法開始"); System.out.println("Thread.currentThread().getName()= "+ Thread.currentThread().getName()); System.out.println("Thread.currentThread().isAlive()= "+ Thread.currentThread().isAlive()); System.out.println("this.getName()= "+this.getName()); System.out.println("this.isAlive()= "+this.isAlive()); System.out.println("構造方法結束"); } @Override public void run() { System.out.println("run方法開始"); System.out.println("Thread.currentThread().getName()= "+ Thread.currentThread().getName()); System.out.println("Thread.currentThread().isAlive()= "+ Thread.currentThread().isAlive()); System.out.println("this.getName()= "+this.getName()); System.out.println("this.isAlive()= "+this.isAlive()); System.out.println("run方法結束"); } public static void main(String[] args) throws InterruptedException { MyThread02 myThread=new MyThread02(); Thread t1=new Thread(myThread); //myThread被t1排程,所以this.isAlive()不是存活的 System.out.println("start t1....isAlive = "+t1.isAlive()); t1.setName("A"); t1.start(); Thread.sleep(1000); System.out.println("end t1....isAlive = "+t1.isAlive()); } }
sleep()
sleep()的作用是在指定的毫秒數內讓當前“正在執行的執行緒”休眠,“正在執行的執行緒”指this.currentThread()返回的執行緒,注意不是this,因為繼承了Thread類,不一定就是this自己排程當前執行緒,可能當前物件構造傳入給Thread t1,t1.start(),則t1才是“正在執行的執行緒”。
例
getId()
getId()方法的作用是取得執行緒的唯一標識