Created
April 18, 2019 21:42
-
-
Save denistsyplakov/e3a7d5deca0630ff28f583f5a33c7f4e to your computer and use it in GitHub Desktop.
Small demo of Condition and ReentrantLock usage
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package ru.yandex.lc.proto.condition; | |
import java.util.concurrent.ArrayBlockingQueue; | |
import java.util.concurrent.ExecutorService; | |
import java.util.concurrent.Executors; | |
import java.util.concurrent.locks.Condition; | |
import java.util.concurrent.locks.ReentrantLock; | |
import java.util.logging.Logger; | |
public class Main { | |
private static Logger log = Logger.getLogger("main"); | |
private static ReentrantLock lock = new ReentrantLock(); | |
private static Condition condition = lock.newCondition(); | |
public static void main(String[] args) throws Exception { | |
ExecutorService exe = Executors.newFixedThreadPool(1); | |
exe.submit(() -> { | |
try { | |
Thread.sleep(2000); | |
log.info("acquiring lock"); | |
lock.lock(); | |
log.info("lock acquired"); | |
try { | |
log.info("unlocking main thread"); | |
condition.signal(); | |
Thread.sleep(2000); | |
} finally { | |
log.info("Releasing lock"); | |
lock.unlock(); | |
} | |
} catch (InterruptedException e) { | |
log.severe(e.toString()); | |
} | |
}); | |
lock.lock(); | |
try { | |
condition.await(); | |
} finally { | |
lock.unlock(); | |
} | |
log.info("main thread unlocked"); | |
exe.shutdownNow(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
12:41:39 AM ru.yandex.lc.proto.condition.Main lambda$main$0 | |
INFO: acquiring lock | |
12:41:39 AM ru.yandex.lc.proto.condition.Main lambda$main$0 | |
INFO: lock acquired | |
12:41:39 AM ru.yandex.lc.proto.condition.Main lambda$main$0 | |
INFO: unlocking main thread | |
12:41:41 AM ru.yandex.lc.proto.condition.Main lambda$main$0 | |
INFO: Releasing lock | |
12:41:41 AM ru.yandex.lc.proto.condition.Main main | |
INFO: main thread unlocked |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment