Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package me.lihongjie;
- import org.junit.Before;
- import org.junit.Test;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- import java.util.concurrent.TimeUnit;
- import java.util.concurrent.locks.Condition;
- import java.util.concurrent.locks.ReentrantLock;
- public class LockTest {
- // private static Logger logger = LoggerFactory.getLogger(LockTest.class);
- private boolean aNotDone = true;
- private Condition aDoneCnd;
- private ReentrantLock lock;
- private boolean firstRun = true;
- private boolean cNotDone = true;
- private Condition cDoneCnd;
- private Condition bDoneCnd;
- private boolean bNotDone = true;
- @Before
- public void setUp() throws Exception {
- lock = new ReentrantLock();
- aDoneCnd = lock.newCondition();
- bDoneCnd = lock.newCondition();
- cDoneCnd = lock.newCondition();
- }
- @Test
- public void test() throws Exception {
- ExecutorService threadPool = Executors.newFixedThreadPool(3);
- threadPool.submit(() -> {
- for (int i = 0; i < 10; i++) {
- lock.lock();
- // logger.info("a get lock");
- if (firstRun) {
- System.out.println("A");
- firstRun = false;
- }else{
- while (cNotDone) {
- try {
- cDoneCnd.await();
- } catch (InterruptedException e) {
- Thread.currentThread()
- .interrupt();
- }
- }
- System.out.println("A");
- }
- aNotDone = false;
- cNotDone = true;
- aDoneCnd.signal();
- lock.unlock();
- // logger.info("a release lock");
- }
- });
- threadPool.submit(() -> {
- for (int i = 0; i < 10; i++) {
- lock.lock();
- // logger.info("b get lock");
- while (aNotDone) {
- try {
- aDoneCnd.await();
- } catch (InterruptedException e) {
- Thread.currentThread()
- .interrupt();
- }
- }
- System.out.println("B");
- aNotDone = true;
- bNotDone = false;
- bDoneCnd.signal();
- lock.unlock();
- // logger.info("b release lock");
- }
- });
- threadPool.submit(() -> {
- for (int i = 0; i < 10; i++) {
- lock.lock();
- // logger.info("c get lock");
- while (bNotDone) {
- try {
- bDoneCnd.await();
- } catch (InterruptedException e) {
- Thread.currentThread()
- .interrupt();
- }
- }
- System.out.println("C");
- bNotDone = true;
- cNotDone = false;
- cDoneCnd.signal();
- lock.unlock();
- // logger.info("c release lock");
- }
- });
- threadPool.awaitTermination(1, TimeUnit.HOURS);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement