Posted on 2009-06-02 20:37
啥都寫點 閱讀(168)
評論(0) 編輯 收藏 所屬分類:
J2SE
關鍵技術:
- 調用線程A的join方法表示當前線程必須等待線程A運行完后才能夠繼續運行。
- 可以為join提供參數,指定當前線程的最長等待時間(毫秒數)。
package book.thread;
/**
* 線程的結合。
* 當一個線程需要等待另一個線程結束時,叫做線程的結合。
*/
public class JoinThread {
/** 自定義線程類 */
static class ThreadA extends Thread{
//線程的ID
private int ID = 0;
//線程運行時循環的次數
private int whileTimes = 0;
public ThreadA(int id, int times){
this.ID = id;
this.whileTimes = times;
}
public void run(){
System.out.println("ThreadA" + this.ID + " begin!");
int i=0;
try {
//連續循環whileTimes次
while (i < this.whileTimes){
System.out.println("ThreadA-" + this.ID + ": " + i++);
//sleep方法將當前線程休眠。
Thread.sleep(200);
}
} catch (InterruptedException e) {
}
System.out.println("ThreadA" + this.ID + " end!");
}
}
public static void main(String[] args) {
//新建4個線程對象
Thread thread1 = new ThreadA(1, 3);
Thread thread2 = new ThreadA(2, 2);
Thread thread3 = new ThreadA(3, 2);
Thread thread4 = new ThreadA(4, 4);
//啟動所有線程
System.out.println("Main method begin. To start 4 threads!");
thread1.start();
thread2.start();
thread3.start();
thread4.start();
//等待所有線程運行結束
try {
thread1.join();
thread2.join();
thread3.join();
thread4.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
//此時所有線程都運行結束
System.out.println("Main method end! All 4 threads are ended");
}
}
--
學海無涯