14.10 同步器
Java.util.concurrent 包中有一些包含预支功能的线程集相关的类型
CyclicBarrier | 公共栅栏,可以约定指定书目的线程到达指定起点后再执行 |
CountDownLatch | 线程集等待知道计数器变0 |
Exchanger | 交换两个线程对象 |
Semaphore | 线程集等待直到允许继续运行 |
SynchronousQueue | 线程把对象交给另一个线程 |
14.10.1 信号量
相当于有限的许可证,通过颁发指定书目的许可,限制可通过线程数量。任意线程可消耗许可,也可释放许可,无需保证获取者释放许可。
Semaphore semaphore = new Semaphore(10);//创建大小为10的信号量
semaphore.acquire();//获取许可,许可为0时阻塞
semaphore.release();//释放许可
❤🧡💛💚💙💜🤎🖤❤🧡💛💚💙💜🤎🖤❤🧡💛💚💙💜🤎🖤
public class Main{
public static void main(String[] args) throws InterruptedException {
Main solution = new Main();
Semaphore semaphore = new Semaphore(10);
for(int i = 0; i < 50; i++){
Thread t = new Thread(new A(semaphore,"number "+i));
t.start();
}
Thread.sleep(8000);
}
}
class A implements Runnable{
private Semaphore semaphore;
private String name;
public A(Semaphore semaphore,String name){
this.semaphore = semaphore;
this.name = name;
}
@Override
public void run() {
try {
semaphore.acquire();
System.out.println(name+" is Running"+new Date().getTime()/1000);
Thread.sleep(1000);
semaphore.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
❤🧡💛💚💙💜🤎🖤❤🧡💛💚💙💜🤎🖤❤🧡💛💚💙💜🤎🖤
运行结果:
每秒有10条同时运行的结果
🚗🚓🚕🛺🚙🚌🚐🚎🚑🚒🚚🚛🚜🚘🚔🚖🚍🦽🦼🛹🚲🛴🛵🏍
🚗🚓🚕🛺🚙🚌🚐🚎🚑🚒🚚🚛🚜🚘🚔🚖🚍🦽🦼🛹🚲🛴🛵🏍
14.10.2 倒计时门栓
线程集等待计数,直到计数变为0,一旦计数为0,不可重用。
CountDownLatch c = new CountDownLatch(10);//创建大小为10的倒计时门栓
C.countDown();//倒计时计数减1
C.await();//等待,直到倒计时为0
❤🧡💛💚💙💜🤎🖤❤🧡💛💚💙💜🤎🖤❤🧡💛💚💙💜🤎🖤
public class Main{
public static void main(String[] args) throws InterruptedException {
Main solution = new Main();
CountDownLatch c = new CountDownLatch(10);
for(int i = 0; i < 10; i++){
Thread t = new Thread(new A(c,"number "+i));
t.start();
Thread.sleep(1000);
}
}
}
class A implements Runnable{
private CountDownLatch c;
private String name;
public A(CountDownLatch c,String name){
this.c = c;
this.name = name;
}
@Override
public void run() {
try {
c.countDown();
c.await();
System.out.println(name+" is Running"+System.currentTimeMillis());
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
❤🧡💛💚💙💜🤎🖤❤🧡💛💚💙💜🤎🖤❤🧡💛💚💙💜🤎🖤
运行结果:
10个不同时启动的线程,可通过倒计时器同时开始执行
🚗🚓🚕🛺🚙🚌🚐🚎🚑🚒🚚🚛🚜🚘🚔🚖🚍🦽🦼🛹🚲🛴🛵🏍
🚗🚓🚕🛺🚙🚌🚐🚎🚑🚒🚚🚛🚜🚘🚔🚖🚍🦽🦼🛹🚲🛴🛵🏍
相关内容:选择 《Java核心技术 卷1》查找相关笔记
评论🌹点赞👍收藏✨关注👀,是送给作者最好的礼物,愿我们共同学习,一起进步