Op dit moment ben ik bezig met concurrency in Java. Met het wait/notify mechanisme heb ik nog wat moeite. Bijvoorbeeld:
Probleem is dat niet uit de waiting loop wordt gesprongen. Na de call naar notify(), zou de thread interrupted moeten zijn en dus uit de loop moeten springen en de melding moeten geven dat het wachten voorbij is. Ipv daarvan wordt wait() nogmaals aangeroepen en blijft de thread eeuwig wachten. Hoe kan ik zorgen dat de loop wordt beeindigd als notify() wordt aangeroepen?
code:
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
| public class WaitingNotify1 { public static void main(String [] args) { ExecutorService executer=Executors.newCachedThreadPool(); WaitingThread waitingThread=new WaitingThread(); executer.execute(waitingThread); executer.execute(new NotifyThread(waitingThread)); } } class WaitingThread implements Runnable { @Override public void run() { try { while (!Thread.interrupted()) { System.out.println("Call wait()"); synchronized (this) { wait(); } System.out.println("wait() called"); } System.out.println("Waiting finished"); } catch (InterruptedException e) { } } } class NotifyThread implements Runnable { private final WaitingThread waitingThread; public NotifyThread(WaitingThread waitingThread) { this.waitingThread=waitingThread; } @Override public void run() { try { synchronized (waitingThread) { System.out.println("Sleep 1 second"); TimeUnit.SECONDS.sleep(1); System.out.println("Call notifyAll()"); waitingThread.notifyAll(); System.out.println("notifyAll() called"); } } catch (InterruptedException e) { } } } Output: Call wait() Sleep 1 second Call notifyAll() notifyAll() called wait() called Call wait() |
Probleem is dat niet uit de waiting loop wordt gesprongen. Na de call naar notify(), zou de thread interrupted moeten zijn en dus uit de loop moeten springen en de melding moeten geven dat het wachten voorbij is. Ipv daarvan wordt wait() nogmaals aangeroepen en blijft de thread eeuwig wachten. Hoe kan ik zorgen dat de loop wordt beeindigd als notify() wordt aangeroepen?