Java Concurrent

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值