u04-1
This commit is contained in:
parent
c982fedf6f
commit
7fcaefa546
|
@ -0,0 +1 @@
|
|||
*.class
|
|
@ -0,0 +1,28 @@
|
|||
class Exchanger<T> {
|
||||
T ex1 = null;
|
||||
T ex2 = null;
|
||||
|
||||
public synchronized T exchange(T obj) throws InterruptedException {
|
||||
T res = null;
|
||||
|
||||
while (ex2 != null) wait();
|
||||
|
||||
if (ex1 == null) {
|
||||
ex1 = obj;
|
||||
while (ex2 == null) wait();
|
||||
|
||||
res = ex2;
|
||||
ex2 = null;
|
||||
|
||||
} else {
|
||||
ex2 = obj;
|
||||
|
||||
res = ex1;
|
||||
ex1 = null;
|
||||
}
|
||||
|
||||
notifyAll();
|
||||
|
||||
return res;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,57 @@
|
|||
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());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
Loading…
Reference in New Issue