Skip to content

Instantly share code, notes, and snippets.

@lihongjie0209
Created March 21, 2019 10:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lihongjie0209/72062b5b7bf05a42ffe51f464824c38e to your computer and use it in GitHub Desktop.
Save lihongjie0209/72062b5b7bf05a42ffe51f464824c38e to your computer and use it in GitHub Desktop.
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);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment