import java.util.concurrent.CountDownLatch;
/**
* (闭锁)计数器,利用它可以实现类似计数器的功能,
比如有一个任务A,他要等到4个任务执行完毕之后才能执行,此时利用CountDownlatch可以实现
* @author jwt
* @date 2019年11月16日
*/
public class MyCountDownlatch {
public static void main(String[] args) throws InterruptedException {
CountDownLatch c = new CountDownLatch(2);
Thread t1 = new MyThread(c);
Thread t2 = new MyThread(c);
t1.start();
t2.start();
c.await();
System.out.println("主线程执行完毕");
}
}
class MyThread extends Thread{
private CountDownLatch c;
public MyThread(CountDownLatch c){
this.c = c;
}
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
System.out.println(Thread.currentThread().getName());
System.out.println("count:"+c.getCount());
c.countDown();
System.out.println("count:"+c.getCount());
}
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
/**
* 回环栅栏
* CyclicBarrier初始化时规定一个数,然后计算调用Cyclicbarrier.await()进入等待的线程数,
* 当线程数达到了这个数目时,所有进入等待状态的线程被唤醒并继续。
* 可以把它看成是一个障碍,所有线程必须到齐后才能一起通过这个障碍
* 初始是可带一个Runnable参数,此Runnable任务和在CyclicBarrier的数达到后,所有其它线程被唤醒前被执行
* @author jwt
* @date 2019年11月16日
*/
public class MyCyclicBarrier {
public static void main(String[] args) {
CyclicBarrier barrier = new CyclicBarrier(4);
new Writer(barrier).start();
new Writer(barrier).start();
new Writer(barrier).start();
new Writer(barrier).start();
}
}
class Writer extends Thread{
private CyclicBarrier barrier;
public Writer(CyclicBarrier barrier){
this.barrier = barrier;
}
@Override
public void run() {
System.out.println(getName()+"开始执行。");
try {
sleep(1000);
} catch (InterruptedException e) {
}
try {
System.out.println("等待的线程数:"+barrier.getNumberWaiting());
barrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
}
System.out.println(getName()+"结束执行。");
}
}
import java.util.concurrent.Semaphore;
/**
* Semaphore(信号量)
* Semaphore是一种基于计数的信号量。它可以设定一个阈值,基于此,多个线程竞争或许许可信号,
* 做自己的申请后归还,超过阈值后,线程申请许可信号将会被阻塞。
* Semaphore可以用来构建一些对象池,资源池之类的,比如数据库连接池,
* 也可以创建计数为1的Semaphore,将其作为一种类似互斥锁的机制,这也叫二元信号量,表示两种互斥状态。
*
* availablePermits 获取当前可用的资源数量
* acquire 申请资源
* release 释放资源
*
* @author jwt
* @date 2019年11月16日
*/
public class MySemaphore {
public static void main(String[] args) {
//三个茅坑,十个人
Semaphore wc = new Semaphore(3);
for(int i = 0;i<10;i++){
new WcThread(wc,"第"+i+"个人").start();;
}
}
}
class WcThread extends Thread{
private String name;
private Semaphore wc;
public WcThread(Semaphore wc,String name){
this.wc = wc;
this.name = name;
}
@Override
public void run() {
int availablePermits = wc.availablePermits(); //可用茅坑数
if(availablePermits >0 ){
System.out.println(name+",有可用茅坑。");
}else{
System.out.println(name+",没有坑。");
}
try {
wc.acquire();//申请资源
System.out.println(name+",进入茅坑。");
Thread.sleep(1000); //模拟蹲茅坑时间
System.out.println(name+",上完了,释放茅坑。");
wc.release();
} catch (InterruptedException e) {
}
}
}
(闭锁)计数器、回环栅栏、信号量
猜你喜欢
转载自blog.csdn.net/administratorJWT/article/details/103097489
今日推荐
周排行