一:FutureTask
public class TestCall {
//callable接口允许抛异常
public static void main(String[] args) throws ExecutionException, InterruptedException {
TestCall2 testCall2 = new TestCall2();
/**
* 因为Callable最终要去走Thread
* 且在Callable无法直接接触到Thread的前提下
* 需要一个中间容器FutureTask来过渡
*/
FutureTask futureTask = new FutureTask(testCall2);
new Thread(futureTask,"Thread1").start();
//接收返回值
Integer o = (Integer) futureTask.get();
System.out.println("输出Callable的返回值"+o);
}
}
//implements Callable<V> 中的<V>参数决定call方法的返回值
class TestCall2 implements Callable<Integer> {
@Override
public Integer call() throws Exception {
System.out.println("call");
return 2;
}
}
二:TestCountDownLach
减法计数器,可以通过先给计数器设置一个固定值,然后在多线程循环的时候依次减减,等到计数器彻底为零的时候,则可以通过 countDownLatch.await();让程序继续向下执行
//计数器
public class TestCountDownLach{
public static void main(String[] args) throws InterruptedException {
//倒计时,设置总数为5
CountDownLatch countDownLatch = new CountDownLatch(5);
for(int i=1;i<6;i++){
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"get number");
//计数器减
countDownLatch.countDown();
},"Thread"+String.valueOf(i)).start();
}
//等待计数器归零,并开始向下执行
countDownLatch.await();
System.out.println("end");
}
}
三:CyclicBarrier
加法计数器
//加法计数器
public class TestCyclicBarrier {
public static void main(String[] args) {
CyclicBarrier cyclicBarrier = new CyclicBarrier(5,()->{
System.out.println("数量上限为5");
});
for(int i=1;i<6;i++){
//i直接拿拿不到,因此采取一个final来接
final Integer number = i;
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"get number"+number);
try {
//如果不达标则会一直等待
cyclicBarrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
},"Thread"+String.valueOf(i)).start();
}
}
}
四:Semaphore
//信号量
public class TestSemaphore {
public static void main(String[] args) {
//线程数量
Semaphore semaphore = new Semaphore(5);
for(int i=1;i<=10;i++){
new Thread(()->{
try {
//得到一个线程许可
semaphore.acquire();
System.out.println(Thread.currentThread().getName()+"得到一个线程许可");
TimeUnit.SECONDS.sleep(1);
System.out.println(Thread.currentThread().getName()+"失去一个线程许可");
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
//释放线程许可
semaphore.release();
}
},"Thread"+String.valueOf(i)).start();
}
}
}