I wrote those examples to show different approaches to sharing results between threads. The whole code is on GitHub. All examples should return "Hello world".
Are these OK from the perspective of data visibility?
The most hardcore one:
import com.google.common.util.concurrent.Uninterruptibles;
import java.util.concurrent.TimeUnit;
public class WaitNotifyExample {
static String result1;
static String result2;
private static final Object object = new Object();
public static void main(String[] args) {
Thread producer1 = new Thread() {
@Override
public void run() {
Uninterruptibles.sleepUninterruptibly(200, TimeUnit.MILLISECONDS);
result1 = "Hello";
synchronized (object) {
object.notify();
}
}
};
Thread producer2 = new Thread() {
@Override
public void run() {
Uninterruptibles.sleepUninterruptibly(400, TimeUnit.MILLISECONDS);
result2 = "world";
synchronized (object) {
object.notify();
}
}
};
producer1.start();
producer2.start();
synchronized (object) {
while(true) {
try {
object.wait();
} catch (InterruptedException e) {
System.out.println("Interrupted!");
}
System.out.println("Notified!");
if(result1 != null && result2 != null) {
System.out.println(result1 + " " + result2);
break;
} else {
System.out.println("Not ready");
}
}
}
}
}