package concurrent;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Auth: zhouhongliang
* Date:2019/8/1
* 多個(gè)線同時(shí)運(yùn)行
* CyclicBarrier
*/
public class CyclicBarrierDemo {
private static CyclicBarrier cyclicBarrier = new CyclicBarrier(5);
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i=0;i<10;i++){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
executorService.execute(()->{
try {
play();
} catch (BrokenBarrierException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
}
public static void play() throws BrokenBarrierException, InterruptedException {
System.out.println(Thread.currentThread().getName() + " 已準(zhǔn)備");
cyclicBarrier.await();
System.out.println(Thread.currentThread().getName() + " 開(kāi)始執(zhí)行");
}
}
輸出結(jié)果:
pool-1-thread-1 已準(zhǔn)備
pool-1-thread-2 已準(zhǔn)備
pool-1-thread-3 已準(zhǔn)備
pool-1-thread-4 已準(zhǔn)備
pool-1-thread-5 已準(zhǔn)備
pool-1-thread-5 開(kāi)始執(zhí)行
pool-1-thread-1 開(kāi)始執(zhí)行
pool-1-thread-2 開(kāi)始執(zhí)行
pool-1-thread-4 開(kāi)始執(zhí)行
pool-1-thread-3 開(kāi)始執(zhí)行
pool-1-thread-3 已準(zhǔn)備
pool-1-thread-5 已準(zhǔn)備
pool-1-thread-1 已準(zhǔn)備
pool-1-thread-4 已準(zhǔn)備
pool-1-thread-2 已準(zhǔn)備
pool-1-thread-2 開(kāi)始執(zhí)行
pool-1-thread-1 開(kāi)始執(zhí)行
pool-1-thread-4 開(kāi)始執(zhí)行
pool-1-thread-5 開(kāi)始執(zhí)行
pool-1-thread-3 開(kāi)始執(zhí)行
網(wǎng)站設(shè)計(jì)制作過(guò)程拒絕使用模板建站;使用PHP+MYSQL原生開(kāi)發(fā)可交付網(wǎng)站源代碼;符合網(wǎng)站優(yōu)化排名的后臺(tái)管理系統(tǒng);網(wǎng)站建設(shè)、成都網(wǎng)站建設(shè)收費(fèi)合理;免費(fèi)進(jìn)行網(wǎng)站備案等企業(yè)網(wǎng)站建設(shè)一條龍服務(wù).我們是一家持續(xù)穩(wěn)定運(yùn)營(yíng)了十余年的創(chuàng)新互聯(lián)建站網(wǎng)站建設(shè)公司。
Process finished with exit code 0
網(wǎng)頁(yè)名稱:JAVA多線程實(shí)現(xiàn)多個(gè)線程同時(shí)運(yùn)行
當(dāng)前地址:http://jinyejixie.com/article46/ijgceg.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供企業(yè)網(wǎng)站制作、微信公眾號(hào)、ChatGPT、Google、關(guān)鍵詞優(yōu)化、網(wǎng)站內(nèi)鏈
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)