Last active
August 29, 2015 13:56
-
-
Save YuriDenison/8913493 to your computer and use it in GitHub Desktop.
thread test
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
// 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