国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > Java > 正文

Java線程編程中isAlive()和join()的使用詳解

2019-11-26 14:57:21
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

一個(gè)線程如何知道另一線程已經(jīng)結(jié)束?Thread類提供了回答此問(wèn)題的方法。

有兩種方法可以判定一個(gè)線程是否結(jié)束。第一,可以在線程中調(diào)用isAlive()。這種方法由Thread定義,它的通常形式如下:

  final boolean isAlive( )

如果所調(diào)用線程仍在運(yùn)行,isAlive()方法返回true,如果不是則返回false。但isAlive()很少用到,等待線程結(jié)束的更常用的方法是調(diào)用join(),描述如下:

  final void join( ) throws InterruptedException

該方法等待所調(diào)用線程結(jié)束。該名字來(lái)自于要求線程等待直到指定線程參與的概念。join()的附加形式允許給等待指定線程結(jié)束定義一個(gè)最大時(shí)間。下面是前面例子的改進(jìn)版本。運(yùn)用join()以確保主線程最后結(jié)束。同樣,它也演示了isAlive()方法。

// Using join() to wait for threads to finish.class NewThread implements Runnable {  String name; // name of thread  Thread t;  NewThread(String threadname) {    name = threadname;    t = new Thread(this, name);    System.out.println("New thread: " + t);    t.start(); // Start the thread  }  // This is the entry point for thread.  public void run() {    try {      for(int i = 5; i > 0; i--) {        System.out.println(name + ": " + i);        Thread.sleep(1000);      }    } catch (InterruptedException e) {      System.out.println(name + " interrupted.");    }    System.out.println(name + " exiting.");  }}class DemoJoin {  public static void main(String args[]) {    NewThread ob1 = new NewThread("One");    NewThread ob2 = new NewThread("Two");    NewThread ob3 = new NewThread("Three");    System.out.println("Thread One is alive: "+ ob1.t.isAlive());    System.out.println("Thread Two is alive: "+ ob2.t.isAlive());    System.out.println("Thread Three is alive: "+ ob3.t.isAlive());    // wait for threads to finish    try {      System.out.println("Waiting for threads to finish.");      ob1.t.join();      ob2.t.join();      ob3.t.join();    } catch (InterruptedException e) {      System.out.println("Main thread Interrupted");    }    System.out.println("Thread One is alive: "+ ob1.t.isAlive());    System.out.println("Thread Two is alive: "+ ob2.t.isAlive());    System.out.println("Thread Three is alive: "+ ob3.t.isAlive());    System.out.println("Main thread exiting.");  }}

程序輸出如下所示:

New thread: Thread[One,5,main]New thread: Thread[Two,5,main]New thread: Thread[Three,5,main]Thread One is alive: trueThread Two is alive: trueThread Three is alive: trueWaiting for threads to finish.One: 5Two: 5Three: 5One: 4Two: 4Three: 4One: 3Two: 3Three: 3One: 2Two: 2Three: 2One: 1Two: 1Three: 1Two exiting.Three exiting.One exiting.Thread One is alive: falseThread Two is alive: falseThread Three is alive: falseMain thread exiting.

如你所見,調(diào)用join()后返回,線程終止執(zhí)行。

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 锡林浩特市| 彩票| 安图县| 麟游县| 保定市| 庆云县| 竹溪县| 通江县| 玉林市| 祁阳县| 静安区| 滨州市| 吉林省| 芜湖县| 尼勒克县| 南江县| 新河县| 广灵县| 集安市| 柘荣县| 双鸭山市| 灯塔市| 陵水| 海原县| 南溪县| 修水县| 法库县| 通海县| 新乡市| 哈尔滨市| 梁河县| 齐齐哈尔市| 嘉定区| 洛阳市| 聂荣县| 大新县| 铜鼓县| 正镶白旗| 集安市| 论坛| 科尔|