并发
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();
}
}
}
semaphore
public class Send {
public static void main(String[] args) {
//线程数量:停车位
Semaphore semaphore=new Semaphore(3);
for (int i = 0; i <7; i++) {
new Thread(()->{
//acquire()得到
try {
semaphore.acquire();
System.out.println(Thread.currentThread().getName()+"抢到了");
Thread.sleep(2000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
//release释放
semaphore.release();
System.out.println(Thread.currentThread().getName()+"离开了");
}).start();
}
}
}
semaphore.acquire();获得假设已经满了 等待被释放为止
semaphore.release()释放 会将当前的信号量是释放
作用:多个共享资源互斥的使用!并发限流,控制最大的线程数