58 lines
1.6 KiB
Java
58 lines
1.6 KiB
Java
class Worker extends Thread {
|
|
public Worker(Exchanger<String> ex) {
|
|
this.ex = ex;
|
|
}
|
|
public void run() {
|
|
String received = null;
|
|
|
|
try {
|
|
received = ex.exchange("World");
|
|
} catch (InterruptedException e) {
|
|
System.out.println("Worker interrupted :-(");
|
|
}
|
|
System.out.println("Worker received " + received + " in exchange for World");
|
|
|
|
try {
|
|
received = ex.exchange("Hi");
|
|
} catch (InterruptedException e) {
|
|
System.out.println("Worker interrupted :-(");
|
|
}
|
|
System.out.println("Worker received " + received.hashCode() + " in exchange for " + "Hi".hashCode());
|
|
|
|
}
|
|
|
|
private Exchanger<String> ex;
|
|
}
|
|
|
|
public class ExchangerTester {
|
|
private static int N_EXCHANGES = 100; // Set to larger number to test repeated exchange()'s
|
|
public static void main(String[] args) {
|
|
String received = null;
|
|
Exchanger<String> exchanger = new Exchanger<String>();
|
|
for (int i = 0; i < N_EXCHANGES; ++i) {
|
|
new Worker(exchanger).start();
|
|
|
|
try {
|
|
received = exchanger.exchange("Hello");
|
|
} catch (InterruptedException e) {
|
|
System.out.println("Main thread interrupted :-(");
|
|
}
|
|
System.out.println("Main thread received " + received + " in exchange for Hello");
|
|
|
|
try {
|
|
Thread.sleep((long) (Math.random()*10));
|
|
} catch (InterruptedException e) {
|
|
// Being interrupted in a random sleep is still random, so nothing to do here
|
|
}
|
|
|
|
try {
|
|
received = exchanger.exchange("Hi");
|
|
} catch (InterruptedException e) {
|
|
System.out.println("Main thread interrupted :-(");
|
|
}
|
|
System.out.println("Exchange #" + i + ": Main thread received " + received.hashCode() + " in exchange for " + "Hi".hashCode());
|
|
}
|
|
}
|
|
|
|
}
|