您的位置:首页 > 编程语言 > Java开发

Java Concurrent

2015-07-21 23:40 302 查看

Java Concurrent

ExecutorService

ExecutorService exec = Executors.newCachedThreadPool(); // create a cached pool


ExecutorService exec = Executors.newFixedThreadPool(4); // fixed sized thread pool


ExecutorService exec = Executors.newSingleThreadExecutor(); // single thread's pool


ThreadPoolExecutor

ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(3, 6, 2, TimeUnit.HOURS, queue)
;

3, corePoolSize

6, maximunPoolSize

2, keep alive time (idle threads will be gc after such a long time)

TimeUnit.HOURS, time units

queue,
LinkedBlockingQueue<Runnable>
, or
new ArrayBlockingQueue<Runnable>(8)


当新任务在方法 execute(java.lang.Runnable) 中提交时,如果运行的线程少于 corePoolSize,则创建新线程来处理请求(即使存在空闲线程)。如果运行的线程多于 corePoolSize 而少于 maximumPoolSize,则仅当队列(queue)满时才创建新线程。如果设置的 corePoolSize 和 maximumPoolSize 相同,则创建了固定大小的线程池。如果将 maximumPoolSize 设置为基本的无界值(如 Integer.MAX_VALUE),则允许池适应任意数量的并发任务。

# AtomicInteger

AtomicInteger ac = new AtomicInteger();

int index = ac.incrementAndGet();

CountDownLatch

countDown(); // decrease the count by 1


await(); // suspend the current thread until the count becomes 0


CountDownLatch c1 = new CountDownLatch(2); // like the condition in OS


Runnable VS Callable

Runnable和Callable的区别是,

(1)Callable规定的方法是call(),Runnable规定的方法是run().

(2)Callable的任务执行后可返回值,而Runnable的任务是不能返回值得

(3)call方法可以抛出异常,run方法不可以

(4)运行Callable任务可以拿到一个Future对象,表示异步计算的结果。它提供了检查计算是否完成的方法,以等待计算的完成,并检索计算的结果。通过Future对象可以了解任务执行情况,可取消任务的执行,还可获取执行结果。

Semaphore

Semaphore s = new Semaphore(4); // allow at most 4 threads concurrently access a piece of code

s.acquire() ; // try to get the qualification to access a piece of code, wait if the current semaphore is 0

s.release(); // release the lock/semaphore
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: