多線程運行時有待處理線程?試試看下面介紹的這個批量線程同步方法吧
在壹批線程處理程序中 有時必須等到所有線程全部運行完後 才能進行下壹步任務處理 可以采用如下方法解決 創建壹個鎖對象 該鎖對象提供壹個當前線程等待其他線程的方法 見代碼
/**
*
* 此類主要用來處理線程的同步屏蔽模型 比如 壹批線程運行 必須在最後壹個線程運行
* 完後 才能進行下壹步的操作 那麽就可以創建壹個鎖對象 鎖對象提供壹個線程等待其他線程
* 的方法 如果當前線程運行時 還有未運行的線程 則此線程wait 否則 此線程喚醒其他阻塞的
* 線程 進而最終完成線程的運行
* */
public class LockObject {
private int totalThread = ;
private int currentThread = ;
public LockObject(int totalThread) {
? this totalThread = totalThread;
? this currentThread = ;
}
public synchronized void waitForOtherThread() {
? if (this currentThread < this totalThread) {
? this currentThread++;
? try {
this wait();
? } catch (InterruptedException e) {
// TODO Auto generated catch block
e printStackTrace();
? }
? } else {
? this currentThread = ;
? notifyAll();
? }
}
public int getTotalThread() {
? return totalThread;
}
public void setTotalThread(int totalThread) {
? this totalThread = totalThread;
}
public int getCurrentThread() {
? return currentThread;
}
public void setCurrentThread(int currentThread) {
? this currentThread = currentThread;
}
}
批量線程同步機制介紹
此對象提供 二個私有變量 totalThread 的初始值為所運行的線程的總數 currentThread 為當前正在運行的線程數
線程運行時處理完自己的任務後調用方法waitForOtherThread 等待其他線程結束 即當前運行線程數與線程總數的比較
如果運行線程數小於線程總數 則當前運行線程數+ 後 當前線程進入等待狀態 否則 喚醒其他等待線程
見測試程序
public class MyThread extends Thread {
public static LockObject lo = new LockObject( );
public MyThread(String threadName) {
? super(threadName);
}
public void run() {
? System out println(Thread currentThread() getName() + 開始運行 );
? lo waitForOtherThread();
? System out println(Thread currentThread() getName() + 結束運行 );
}
public static void main(String[] args) {
? for (int i = ; i <= ; i++) {
? Thread thread = new MyThread( 第 + i + 個線程 );
? thread setPriority(NORM_PRIORITY);
? thread start();
? }
}
}
lishixinzhi/Article/program/Java/gj/201311/27516