Created
January 15, 2016 10:27
-
-
Save guavabot/45ca5be8d9568d783d9f to your computer and use it in GitHub Desktop.
This file contains 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
/** | |
* Proves that we can put a condition in the parameter of a synchronized block. | |
* | |
* <p>Ex. | |
* <br>{@code synchronized (first ? mLock1 : mLock2)} | |
*/ | |
public class ConditionSynchronizedBlock { | |
public static void main(String [ ] a) { | |
ConditionSynchronizedBlock tested = new ConditionSynchronizedBlock(); | |
new Thread(new Runnable() { | |
public void run() { | |
tested.lock1(); | |
} | |
}).start(); | |
new Thread(new Runnable() { | |
public void run() { | |
tested.acquire(false); | |
tested.acquire(true); | |
} | |
}).start(); | |
} | |
private final Object mLock1 = new Object(); | |
private final Object mLock2 = new Object(); | |
private void lock1() { | |
printThreadMsg("locking first"); | |
synchronized (mLock1) { | |
printThreadMsg("locked first"); | |
try { | |
printThreadMsg("pausing"); | |
Thread.sleep(2_000); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} | |
printThreadMsg("released first"); | |
} | |
private void acquire(boolean first) { | |
printThreadMsg("acquiring " + (first ? "first" : "second")); | |
synchronized (first ? mLock1 : mLock2) { | |
printThreadMsg("acquired " + (first ? "first" : "second")); | |
} | |
printThreadMsg("released " + (first ? "first" : "second")); | |
} | |
private void printThreadMsg(String msg) { | |
String fullMsg = String.format("%d %s: %s", System.nanoTime(), Thread.currentThread().getName(), msg); | |
System.out.println(fullMsg); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment