JUC下的几种线程计数器以及读写锁
2021-05-04 04:30
标签:tran alt dwr ide tree rac trace ati time 读读可共享--写读、写写要独占 JUC下的几种线程计数器以及读写锁 标签:tran alt dwr ide tree rac trace ati time 原文地址:https://blog.51cto.com/14234228/2506979package thread20200414;
import java.util.concurrent.CountDownLatch;
/**
CountDownLaunch做线程减法,即所有线程执行完后,才可以进行下一步
一个线程等待其他线程执行完毕后,才执行
* @author zhaomin
* @date 2020/4/15 8:35
*/
public class CountDownLanchTest {
public static void main(String[] args) {
CountDownLatch countDownLatch=new CountDownLatch(6);
for(int i=0;i{
System.out.println(Thread.currentThread().getName()+"--离开教室");
countDownLatch.countDown();
},String.valueOf(i)).start();
}
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("main离开教室");
}
}
2- CyclicBarrier--JUC
package thread20200414;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
/**
* 线程加法,只有等到一定数量的线程都开启后,才进行下一步(执行runnable里的方法)
* @author zhaomin
* @date 2020/4/15 8:51
*/
public class CyclicBarrierTest {
public static void main(String[] args) {
Runnable runnable=new Runnable() {
@Override
public void run() {
System.out.println("集齐7颗龙珠,召唤神龙");
}
};
CyclicBarrier cyclicBarrier=new CyclicBarrier(7,runnable);
for(int i=0;i{
System.out.println(count+"颗龙珠");
try {
cyclicBarrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
},String.valueOf(i)).start();
}
}
}
3-Semaphore--JUC
package thread20200414;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
/**
* 抢车位,狼多肉少-3个资源6和线程
* @author zhaomin
* @date 2020/4/15 15:06
*/
public class SemaphoreTest {
public static void main(String[] args) {
Semaphore semaphore=new Semaphore(3);
for(int i=1;i{
try {
semaphore.acquire();//获取到了资源,就让资源数减一
System.out.println(Thread.currentThread().getName()+"抢占车位");
TimeUnit.SECONDS.sleep(3);
System.out.println(Thread.currentThread().getName()+"离开车位");
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
semaphore.release();//释放资源就让资源加一
}
},String.valueOf(i)).start();
}
}
}
4-读写锁
package thread20200414;
import com.sun.org.apache.xpath.internal.SourceTree;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* 读写锁
* 读读可同时
* 读写、写写要独占
* @author zhaomin
* @date 2020/4/15 16:10
*/
class Book{
private volatile Map
上一篇:交换排序之冒泡排序(java)