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>
, ornew 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
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-29 19:13:32