1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
|
import java.util.HashSet;
import java.util.Set;
public class TestEventNotifyALL {
public final class Event {
Set<MyRunnable> myRunnableSet=new HashSet<MyRunnable>();
// notify all waits on this event
public final synchronized void wakeUp() {
/*
*/
for (MyRunnable myRunnable:myRunnableSet) {
myRunnable.setStatus(true);
}
myRunnableSet.clear();
notifyAll();
System.out.println("WAKE UP AND SEE IF YOUR STATUS WAS CHANGED BY ME...");
}
public final synchronized void waitOnMySignal(MyRunnable myRunnable) throws InterruptedException {
//System.out.println(Thread.currentThread().getName()+"... IS NOW WAITING ON ME");
myRunnableSet.add(myRunnable);
wait(); //
}
}
public int a = 0;
Event event = new Event();
public TestEventNotifyALL() {
new Thread() {
public void run() {
for (int i = 0; i < 5; i += 1) {
a = i;
event.wakeUp();
try {
Thread.sleep(5);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}.start();
callThread("T1"); // creation thread 1
callThread("T2"); // creation thread 2
callThread("T3"); // creation thread 3
callThread("T4"); // creation thread 4
callThread("T5"); // creation thread 5
}
public class MyRunnable implements Runnable {
private volatile boolean status = false;
public void run() {
for (int i = 0; i < 5; i += 1) {
waiting();
System.out.println(Thread.currentThread().getName()+"..."+a);
}
}
public final void waiting() {
while (status == false) {
try {
event.waitOnMySignal(this);
} catch (InterruptedException e) {
}
}
status=false;
}
public void setStatus(boolean status) {
this.status = status;
}
}
private void callThread(final String name) {
Thread t=new Thread(new MyRunnable(),name);
t.start();
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new TestEventNotifyALL();
}
} |
Partager