Created
May 14, 2016 10:18
-
-
Save nikkatsa/9f3d3840ac0d29d2fb1f8a79cf6b45d8 to your computer and use it in GitHub Desktop.
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
public void start() { | |
final ExecutorService left = Executors.newSingleThreadExecutor(new NamedThreadFactory("Left", true)); | |
final Object leftObject = new Object(); | |
final ExecutorService right = Executors.newSingleThreadExecutor(new NamedThreadFactory("Right", false)); | |
final Object rightObject = new Object(); | |
left.execute(() -> { | |
while (true) { | |
synchronized (leftObject) { | |
ThreadUtils.sleepWithoutInterruption(3000L, TimeUnit.MILLISECONDS); | |
log.info("Got left object, trying to acquire right now"); | |
synchronized (rightObject) { | |
log.info("Got right object"); | |
throw new RuntimeException("Shouldn't get both objects"); | |
} | |
} | |
} | |
}); | |
right.execute(() -> { | |
while (true) { | |
synchronized (rightObject) { | |
ThreadUtils.sleepWithoutInterruption(3000L, TimeUnit.MILLISECONDS); | |
log.info("Got right object, trying to acquire left now"); | |
synchronized (leftObject) { | |
log.info("Got left object"); | |
throw new RuntimeException("Shouldn't get both objects"); | |
} | |
} | |
} | |
}); | |
try { | |
Thread.currentThread().join(); | |
} catch (final InterruptedException e) { | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment