并发
Callable
1 可以返回值
2可以抛出异常
泛型指的是返回值的类型
public class Send {
public static void main(String[] args) {
//怎么启动Callable
//new Thread().start();
Aaa thread=new Aaa();
FutureTask futureTask=new FutureTask(thread);
new Thread(futureTask,"name").start();
}
}
class Aaa implements Callable<String> {
@Override
public String call() throws Exception {
System.out.println("sssss");
return "ssss";
}
}
CountDownLatch
value(of)返回本身的值
每次有线程调用countDown()数量-1,假设计数器变为0,countDownLatch.await()就会被唤醒,继续执行!
public class Send {
public static void main(String[] args) throws InterruptedException {
//倒计时
CountDownLatch count=new CountDownLatch(6);
for (int i = 0; i < 6; i++) {
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"GO out");
count.countDown();//数量-1
},String.valueOf(i)).start();
}count.await();//等待计数器归零然后在向下执行
}
}
CyclicBarrier
public class Send {
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;
//lambda能操作i吗 线程里只能通过final类型的的变量操作i
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"收集了"+temp);
try {
cyclicBarrier.await();//等待
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (BrokenBarrierException e) {
throw new RuntimeException(e);
}
}).start();
}
}
}