1、Callable
1、可以有返回值
2、可以抛出异常
3、方法不同、run()/call()
future Task
细节:
1、有缓存
2、结果可能需要等待,会阻塞
2、常用的辅助类
2.1 CountDownLatch
package com.add; import java.util.concurrent.CountDownLatch; //计数器 public class CountDownLatchDemo { public static void main(String[] args) throws InterruptedException { //总数是6 CountDownLatch countDownLatch = new CountDownLatch(6); for (int i = 0; i < 6; i++) { new Thread(()->{ System.out.println(Thread.currentThread().getName()+"-->GO OUT"); countDownLatch.countDown();//减法操作 },String.valueOf(i)).start(); } countDownLatch.await();//判断是否到零,到零执行下一步 System.out.println("Close"); } }
2.2 CyclicBarrier
package com.add; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; public class CyclicBarrierDemo { public static void main(String[] args) { //召唤龙珠 CyclicBarrier cyclicBarrier = new CyclicBarrier(7,()->{ System.out.println("召唤神龙成功"); }); for (int i = 0; i <7 ; i++) { final int temp = i; new Thread(()->{ System.out.println(Thread.currentThread().getName()+"收集了"+temp+"个龙珠"); try { cyclicBarrier.await(); } catch (InterruptedException e) { e.printStackTrace(); } catch (BrokenBarrierException e) { e.printStackTrace(); } }).start(); } } }
2.3 Semaphore
package com.add; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; public class SemaphoreDemo { public static void main(String[] args) { Semaphore semaphore = new Semaphore(3); for (int i = 0; i <6 ; i++) { new Thread(()->{ //acquire()得到 try { semaphore.acquire(); System.out.println(Thread.currentThread().getName()+"--->抢到停车位"); TimeUnit.SECONDS.sleep(2); System.out.println(Thread.currentThread().getName()+"--->离开停车位"); } catch (InterruptedException e) { e.printStackTrace(); } finally { semaphore.release(); } //release()释放 },String.valueOf(i)).start(); } } }
原理
semaphore.acquire(); 获得,假设如果已经满了,等待,等待被释放为止
semaphore.release(); 释放,会将当前的信号量释放+1,然后唤醒等待的线程
作用:多个共享资源互斥的使用,并发限流,控制最大的线程数。