I\'m trying to understand thread basics, and as a first example I create two thread that write a String on the stdout. As I know the scheduler allows to execute the threads
In conclusion to my discussion with Brian Agnew, I submit this code that uses java.util.concurrent.Phaser
to coordinate your ping-pong threads:
static final Phaser p = new Phaser(1);
public static void main(String[] args) {
t("ping");
t("pong");
}
private static void t(final String msg) {
new Thread() { public void run() {
while (true) {
System.out.println(msg);
p.awaitAdvance(p.arrive()+1);
}
}}.start();
}
The key difference between this solution and the one you attempted to code is that your solution busy-checks a flag, thereby wasting CPU time (and energy!). The correct approach is to use blocking methods that put a thread to sleep until it is notified of the relevant event.