執行緒協作類總結

2021-08-18 18:16:41 字數 2666 閱讀 3362

1、 countdownlatch允許乙個或多個執行緒等待其他執行緒完成操作。當等待操作完成時,主線程繼續往下執行

/**

* 當 countdownlatch.await(); 方法觸發時,必須等待執行指定次數的countdownlatch.countdown();方法後,才能繼續往下執行

* @param args

* @throws interruptedexception

*/    public static void main(string args) throws interruptedexception catch (interruptedexception e) {}

system.out.println("執行任務[" + number + "]");

countdownlatch.countdown();

system.out.println("完成任務[" + number + "]");}};

thread thread = new thread(runnable);

thread.start();

}system.out.println("主線程開始等待...");

//當執行這個方法後,需要等待  countdownlatch.countdown();執行10次才能放棄等待

countdownlatch.await();

system.out.println("主線程執行完畢...");

}

2、cyclicbarrier 方法,保證所有執行緒在同一起跑線上開始執行。當執行cyclicbarrier 的await方法時,這個執行緒被中斷了,只有指定個數的await方法執行完成時,當前執行緒才能繼續網下執行,也可以用來完成countdownlatch的操作。

/**

* cyclicbarrier 當cyclicbarrier.await();這個被觸發時,cyclicbarrier.await();必須被執行10次後才會被喚醒

* @param args

*/public static void main(string args) catch (interruptedexception e) {}

system.out.println("等待執行任務[" + number + "]");

try catch (interruptedexception e) catch (brokenbarrierexception e)

system.out.println("開始執行任務[" + number + "]");}};

thread thread = new thread(runnable);

thread.start();

}}

3、semaphore(訊號量)是用來控制同時訪問特定資源的執行緒數量,它通過協調各個執行緒,以保證合理的使用公共資源

/**

* semaphore.acquire();執行時,獲取乙個許可證,當獲取的許可證超過設定數目時,執行緒進入阻塞等待階段,通過semaphore.release();

* 可以釋放許可證

* @param args

* @throws interruptedexception

*/public static void main(string args) throws interruptedexception catch (interruptedexception e) {}

try

semaphore.release();

} catch (interruptedexception e) {}}};

thread thread = new thread(runnable);

thread.start();

}thread.sleep(1000);

system.out.println("共" + number.get() + "個執行緒獲得到訊號");

system.exit(0);

}

3、exchanger(交換者)是乙個用於執行緒間協作的工具類。exchanger用於進行執行緒間的資料交換。它提供乙個同步點,在這個同步點,兩個執行緒可以交換彼此的資料。這兩個執行緒通過exchange方法交換資料,如果第乙個執行緒先執行exchange()方法,它會一直等待第二個執行緒也執行exchange方法,當兩個執行緒都到達同步點時,這兩個執行緒就可以交換資料,將本執行緒生產出來的資料傳遞給對方。

/**

* 當現場執行到 string content = exchanger.exchange("thread1"); 等待另外乙個執行此方法,交換資料

* @param args

* @throws interruptedexception

*/public static void main(string args) throws interruptedexception catch (interruptedexception e) {}

}});

thread thread2 = new thread(new runnable() catch (interruptedexception e) {}

}});

thread1.start();

thread2.start();

}

執行緒 同步執行緒和協作執行緒

1 同步塊 實現 package edu.xalead public class 吃包子 extends thread public synchronized void eat public void run catch interruptedexception e 多執行緒的爭用問題 會出現兩個執...

執行緒 執行緒協作 管程法

wait 讓執行緒堵塞 notifyall 通知執行緒接觸堵塞mq 的思想,列 生產者生產,消費者消費,通過緩衝區 生產者生產100個摸頭,消費者買饅頭。消費者從緩衝區取饅頭,如果饅頭已賣完,就進入等待,等生產者做饅頭,放到容器裡,再通知消費者取饅頭,如果生產者已經再容器裡生產100個 則 進入等待...

執行緒 角色與協作

多執行緒使用場景 主 控 執行緒召喚了幾個小弟來解決主 控 執行緒不方便處理的問題 召喚乙個小弟或召喚一群小弟,各有分工,協同完成任務。普通的程式塊通過if else等流控來控制業務流程 執行緒通過執行緒變數來控制 與人類社會 公司組織 類似,執行緒程式設計的主要思想是任務分解 分離與匯報機制 執行...