這是一個來自《Java編程思想》上的示例。 下載見 http://www.linuxidc.com/Linux/2011-11/48069.htm
- package demo.thread;
-
- /**
- *sleep()是靜態方法,是屬於類的,作用是讓當前線程阻塞
- *join()是使線程同步,如在某個線程裡調用t.join()表示t線程執行完再執行當前線程
- *interrupt()給線程設定一個標志表示該線程已被中斷,但在異常捕獲時將清理這個標志
- *所以在catch子句中,該標志為false
- */
- public class SleepJoinDemo {
- public static void main(String[] args) {
- Sleeper sleep1 = new Sleeper("sleep1", 1500);
- Sleeper sleep2 = new Sleeper("sleep2", 1500);
- Joiner join1 = new Joiner("join1", sleep1);
- Joiner join2 = new Joiner("join2", sleep1);
- sleep2.interrupt();
- }
- }
-
- class Sleeper extends Thread {
- // 可以傳參設定睡眠時間
- private int sleepTime;
-
- public Sleeper(String name, int sleepTime) {
- super(name);
- this.sleepTime = sleepTime;
- start();// 在構造方法中啟動
- }
-
- @Override
- public void run() {
- try {
- sleep(sleepTime);
- } catch (InterruptedException e) {
- System.out.println(getName() + " was interrupted.\n"
- + "isInterrupted():" + isInterrupted());
- return;
- }
- System.out.println(getName() + " has awakened");
- }
- }
-
- class Joiner extends Thread {
- private Sleeper sleeper;
-
- public Joiner(String name, Sleeper sleeper) {
- super(name);
- this.sleeper = sleeper;
- start();
- }
-
- public void run() {
- try {
- sleeper.join();//合並,異步變同步
- } catch (InterruptedException e) {
- System.out.println("interrupted");
- }
- System.out.println(getName() + " join completed");
- }
- }