Skip to content

Instantly share code, notes, and snippets.

@YuriDenison
Last active August 29, 2015 13:56
Show Gist options
  • Save YuriDenison/8913493 to your computer and use it in GitHub Desktop.
Save YuriDenison/8913493 to your computer and use it in GitHub Desktop.
thread test
// Update to get Worker-0 -> Worker-1 -> Worker-0... order
public class Main {
public static void main(String[] args) {
new Thread(new Worker()).start();
new Thread(new Worker()).start();
}
static class Worker implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName());
}
}
}
}
// answer
public class Main {
public static void main(String[] args) {
new Thread(new Worker()).start();
new Thread(new Worker()).start();
}
static class Worker implements Runnable {
@Override
public void run() {
synchronized(Worker.class) {
for (int i = 0; i < 10; i++) {
try {
Worker.class.notifyAll();
System.out.println(Thread.currentThread().getName());
Worker.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Worker.class.notifyAll();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment