juc工具类
CyclicBarrier:
栅栏循环,定义一个数的最终数值,可以使得线程的调度有序的执行,先将循环当中的数输出完成然后再进行判断如果为0,则结束最后进行lambda表达式当中的方法,有序的进行。
public class CycDemo {
private static final int NUMBER=7;
public static void main(String[] args) {
//栅栏循环
CyclicBarrier cc = new CyclicBarrier(NUMBER,()->{
System.out.println("集齐七颗龙珠召唤神龙");
});
for (int i = 0; i <=6 ; i++) {
new Thread(()->{
System.out.println(Thread.curren`在这里插入代码片`tThread().getName()+"颗龙珠");
try {
cc.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
},String.valueOf(i)).start();
}
}
}
栅栏的实现:
/**
* Returns the number of parties currently waiting at the barrier.
* This method is primarily useful for debugging and assertions.
*
* @return the number of parties currently blocked in {@link #await}
*/
public int getNumberWaiting() {
final ReentrantLock lock = this.lock;//可重入锁 非公平锁
lock.lock();//上锁
try {
return parties - count;
} finally {
lock.unlock();//进行解锁
}
}
Semaphore信号灯:
//六个车位三辆车抢车位
public class SemaphoreDemo {
public static void main(String[] args) throws InterruptedException {
Semaphore ss = new Semaphore(3);
for (int i = 0; i <=5 ; i++) {
ss.acquire();
new Thread(()->{
try {
System.out.println(Thread.currentThread().getName()+"辆车抢到了车位");
TimeUnit.SECONDS.sleep(new Random().nextInt(5));//休眠的秒数
System.out.println(Thread.currentThread().getName()+"辆车释放了车位");
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
ss.release();
}
},String.valueOf(i)).start();
}
}
}```
acquire
release

被折叠的 条评论
为什么被折叠?



