Skip to content

Instantly share code, notes, and snippets.

@volkov
Created September 13, 2016 20:41
Show Gist options
  • Save volkov/50fca2c81b759f32f828c13e182d42c4 to your computer and use it in GitHub Desktop.
Save volkov/50fca2c81b759f32f828c13e182d42c4 to your computer and use it in GitHub Desktop.
public class Test {
private static List<String> messageQueue = new ArrayList<>();
private static void put(String message) {
synchronized (messageQueue) {
messageQueue.add(message);
messageQueue.notify();
}
}
private static String get() throws InterruptedException {
synchronized (messageQueue) {
while (true) {
if (!messageQueue.isEmpty()) {
final String result = messageQueue.get(0);
messageQueue.remove(0);
return result;
} else {
messageQueue.wait();
}
}
}
}
public static void main(String[] args) throws InterruptedException {
final Thread thread = new Thread(() -> {
while (true) {
try {
System.out.println(Thread.currentThread().getName() + " " + get());
} catch (InterruptedException e) {
System.out.println("Interrupted");
return;
}
}
});
//thread.setDaemon(true);
thread.start();
for (int i = 0; i < 10; i++) {
put("message" + i);
Thread.sleep(1000);
}
thread.interrupt();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment