cyclicbarrier java_Java并发编程之CyclicBarrier和线程池的使用
原標(biāo)題:Java并發(fā)編程之CyclicBarrier和線程池的使用
下面我們來講述一下線程池和CyclicBarrier的使用和對比。
一、場景描述
有四個游戲玩愛好者玩游戲,游戲中有三個關(guān)卡,每一個關(guān)卡必須讓所有玩家到達后才能允許通過。其實這個場景里的玩家中如果有玩家B先到了第一個關(guān)卡,他必須要等到其他剩余玩家都到達第一個關(guān)卡時才能通過,這也說明了線程之間需要相互等待。這和CountDownLatch的應(yīng)用場景有區(qū)別,CountDownLatch里的線程是到了運行的目標(biāo)后繼續(xù)干自己的事情,而不需要管其他玩家,而這里的線程就不同了,必須等待其他玩家。
二、CyclicBarrier介紹
CyclicBarrier 的字面意思是可循環(huán)使用(Cyclic)的屏障(Barrier)。它要做的事情是,讓一組線程到達一個屏障(也可以叫同步點)時被阻塞,直到最后一個線程到達屏障時,屏障才會開門,所有被屏障攔截的線程才會繼續(xù)干活。CyclicBarrier默認的構(gòu)造方法是CyclicBarrier(int parties),其參數(shù)表示屏障攔截的線程數(shù)量,每個線程調(diào)用await方法告訴CyclicBarrier我已經(jīng)到達了屏障,然后當(dāng)前線程被阻塞。
CyclicBarrier類有兩個常用的構(gòu)造方法:
1. CyclicBarrier(int parties)
這里的parties也是一個計數(shù)器,例如,初始化時parties里的計數(shù)是3,于是擁有該CyclicBarrier對象的線程當(dāng)parties的計數(shù)為3時就喚醒,注:這里parties里的計數(shù)在運行時當(dāng)調(diào)用CyclicBarrier:await()時,計數(shù)就加1,一直加到初始的值
2. CyclicBarrier(int parties, Runnable barrierAction)
這里的parties與上一個構(gòu)造方法的解釋是一樣的,這里需要解釋的是第二個入?yún)?Runnable barrierAction),這個參數(shù)是一個實現(xiàn)Runnable接口的類的對象,也就是說當(dāng)parties加到初始值時就出發(fā)barrierAction的內(nèi)容。
代碼示例 package com.itmyhome;import java.util.concurrent.BrokenBarrierException;import java.util.concurrent.CyclicBarrier;/**
輸出結(jié)果: 玩家0正在玩第一關(guān)...玩家3正在玩第一關(guān)...玩家2正在玩第一關(guān)...玩家1正在玩第一關(guān)...所有玩家進入第二關(guān)!
CyclicBarrier和CountDownLatch的區(qū)別
CountDownLatch: 一個線程(或者多個), 等待另外N個線程完成某個事情之后才能執(zhí)行。
CyclicBarrier: N個線程相互等待,任何一個線程完成之前,所有的線程都必須等待。
CountDownLatch的計數(shù)器只能使用一次。而CyclicBarrier的計數(shù)器可以使用reset() 方法重置。所以CyclicBarrier能處理更為復(fù)雜的業(yè)務(wù)場景,比如如果計算發(fā)生錯誤,可以重置計數(shù)器,并讓線程們重新執(zhí)行一次。
CountDownLatch:減計數(shù)方式,CyclicBarrier:加計數(shù)方式
三、線程池使用
在上例中,用到了線程池,采用了Executors提供的靜態(tài)方法初始化線程池。
ExecutorService executorService = Executors.newCachedThreadPool();
newCachedThreadPool()方法實現(xiàn)如下,即初始線程池沒有創(chuàng)建線程,只有在有新任務(wù)時才會創(chuàng)建線程去執(zhí)行任務(wù),空閑線程等待時間60秒。
public static ExecutorService newCachedThreadPool() { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue());
}
ExecutorService與ThreadPoolExecutor是什么關(guān)系,有什么差異,因為通過ThreadPoolExecutor也能夠?qū)崿F(xiàn)線程池。
public class Test { public static void main(String[] args) {
ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 10, 200, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(5)); for(int i=0;i<15;i++){
MyTask myTask = new MyTask(i);
executor.execute(myTask);
}
executor.shutdown();
}
}
首先來看看ThreadPoolExecutor的execute函數(shù),這個函數(shù)返回void:
void execute(Runnable command)//Executes the given task sometime in the future.
然后再來看看ExecutorService的submit函數(shù),這個函數(shù)返回Future,即有返回值,這是兩者的一個差異之處。
Future> submit(Runnable task)//Submits a Runnable task for execution and returns a Future representing that task.
接下來,通過樹狀圖來看看線程池相關(guān)類間的關(guān)系,可以查閱源碼看之間的關(guān)系:
Executor是頂層接口,僅提供execute方法。
ExecutorService接口繼承了Executor接口,豐富了接口函數(shù)。
AbstractExecutorService抽象類實現(xiàn)了ExecutorService接口。
ThreadPoolExecutor類繼承了AbstractExecutorService類。
部分源碼
Executor接口
public interface Executor { void execute(Runnable command);
}
ExecutorService接口
public interface ExecutorService extends Executor { void shutdown(); boolean isShutdown(); boolean isTerminated(); boolean awaitTermination(long timeout, TimeUnit unit)
throws InterruptedException;
Future submit(Callable task);
Future submit(Runnable task, T result);
Future> submit(Runnable task);
List> invokeAll(Collection extends Callable> tasks) throws InterruptedException;
List> invokeAll(Collection extends Callable> tasks, long timeout, TimeUnit unit) throws InterruptedException;
T invokeAny(Collection extends Callable> tasks)
throws InterruptedException, ExecutionException;
T invokeAny(Collection extends Callable> tasks, long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
}
AbstractExecutorService抽象類
public abstract class AbstractExecutorService implements ExecutorService { protected RunnableFuture newTaskFor(Runnable runnable, T value) { }; protected RunnableFuture newTaskFor(Callable callable) { }; public Future> submit(Runnable task) {}; public Future submit(Runnable task, T result) { }; public Future submit(Callable task) { }; private T doInvokeAny(Collection extends Callable> tasks, boolean timed, long nanos)
throws InterruptedException, ExecutionException, TimeoutException {
}; public T invokeAny(Collection extends Callable> tasks)
throws InterruptedException, ExecutionException {
}; public T invokeAny(Collection extends Callable> tasks, long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
}; public List> invokeAll(Collection extends Callable> tasks) throws InterruptedException {
}; public List> invokeAll(Collection extends Callable> tasks, long timeout, TimeUnit unit) throws InterruptedException {
};
}
ThreadPoolExecutor類
public class ThreadPoolExecutor extends AbstractExecutorService {
..... public ThreadPoolExecutor(int corePoolSize,int maximumPoolSize,long keepAliveTime,TimeUnit unit,
BlockingQueue workQueue); public ThreadPoolExecutor(int corePoolSize,int maximumPoolSize,long keepAliveTime,TimeUnit unit,
BlockingQueue workQueue,ThreadFactory threadFactory); public ThreadPoolExecutor(int corePoolSize,int maximumPoolSize,long keepAliveTime,TimeUnit unit,
BlockingQueue workQueue,RejectedExecutionHandler handler); public ThreadPoolExecutor(int corePoolSize,int maximumPoolSize,long keepAliveTime,TimeUnit unit,
BlockingQueue workQueue,ThreadFactory threadFactory,RejectedExecutionHandler handler);
...public void execute(Runnable command) { if (command == null) throw new NullPointerException(); int c = ctl.get(); if (workerCountOf(c) < corePoolSize) { if (addWorker(command, true)) return;
c = ctl.get();
} if (isRunning(c) && workQueue.offer(command)) { int recheck = ctl.get(); if (! isRunning(recheck) && remove(command))
reject(command); else if (workerCountOf(recheck) == 0)
addWorker(null, false);
} else if (!addWorker(command, false)) reject(command);
}
}
歡迎關(guān)注小編,每日更新最新資訊帶給大家。返回搜狐,查看更多
責(zé)任編輯:
總結(jié)
以上是生活随笔為你收集整理的cyclicbarrier java_Java并发编程之CyclicBarrier和线程池的使用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql 5.6 binlog_for
- 下一篇: android native java_