我讀這樣的: How to use wait and notify in Java?代碼沒有使用多線程
我想要實現的等待的例子/通知對生產者/消費者模型在Java中使用線程。
消費者是一個服務器,其中有一個存儲在列表中的對象。可以添加/刪除此列表。
只有消費者服務器存儲了對象(整數),生產者才發送數據(使用PipedInputStream
/PipedOutputStream
),否則生產者停止。當服務器再次有對象時,生產者開始發送數據。
問題興起,當我打電話下一方法
public void addInteger() {
new Thread (new Runnable() {
public void run() {
try {
System.out.println ("Add before size:" + lConsumerClient.size());
lConsumerClient.add((int)(Math.random()*100.0));
synchronized(oSignalExternal) {
oSignalExternal.notify();
}
System.out.println ("Add after size:" + lConsumerClient.size());
} catch (Exception e) { e.printStackTrace(); }
}
}).start();
}
public void removeFirst() {
new Thread (new Runnable() {
public void run() {
try {
System.out.println ("Remove before size:" + lConsumerClient.size());
if (hasInteger()) {
lConsumerClient.remove(0);
}
synchronized(oSignalExternal) {
oSignalExternal.notify();
}
System.out.println ("Remove after size:" + lConsumerClient.size());
} catch (Exception e) { e.printStackTrace(); }
}
}).start();
}
輸出:
Add before size:0
Add after size:1
i:0 ->18 =218
i:0 ->18 =218
Add before size:1
i:0 ->18 =218
i:1 ->90 =290
i:0 ->18 =218
i:1 ->90 =290
Add before size:2
i:0 ->18 =218
i:1 ->90 =290
i:2 ->76 =276
Add before size:3
i:0 ->18 =218
i:1 ->90 =290
i:2 ->76 =276
i:3 ->43 =243
Remove before size:4
Remove before size:3
Remove before size:2
i:0 ->43 =243
i:0 ->43 =243
Remove before size:1
ExtSynchro$ExtClient sleeping
Remove after size:0
Remove after size:0
Remove after size:0
ExtSynchro$ExtClient sleeping
Add after size:0
Add after size:0
Add after size:0
Remove after size:0
等待和通知工作。
我想知道爲什麼調用後:
synchronized(oSignalExternal) {
oSignalExternal.notify();
}
不執行任何代碼?
這裏的完整代碼
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ArrayBlockingQueue;
import javax.swing.*;
public class ExtSynchro extends JFrame {
JButton jbSync = new JButton("Sync");
JButton jbPlus = new JButton("+");
JButton jbMinus = new JButton("-");
JButton jbStop = new JButton("Stop");
Object oSignalExternal = new Object();
ExtServer exConsumerServer;
ExtClient exProducerClient;
PipedInputStream pSnk = new PipedInputStream();
PipedOutputStream pSrc = new PipedOutputStream();
static final String NL = System.getProperty("line.separator");
public ExtSynchro() {
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
jbSync.addActionListener((ActionEvent e) -> {
try { pSrc.connect(pSnk); } catch (IOException ex) {}
exConsumerServer = new ExtServer();
exProducerClient = new ExtClient();
exConsumerServer.start();
exProducerClient.start();
});
jbPlus.addActionListener((ActionEvent e) -> {
exConsumerServer.addInteger();
});
jbMinus.addActionListener((ActionEvent e) -> {
exConsumerServer.removeFirst();
});
jbStop.addActionListener((ActionEvent e) -> {
exConsumerServer.stopThread();
exProducerClient.stopThread();
exConsumerServer = null;
exProducerClient = null;
});
JPanel jpButtons = new JPanel();
jpButtons.setLayout(new BoxLayout(jpButtons, BoxLayout.PAGE_AXIS));
jpButtons.add(jbSync);
jpButtons.add(jbPlus);
jpButtons.add(jbMinus);
jpButtons.add(jbStop);
add(jpButtons);
pack();
}
public static void main(String args[]) {
EventQueue.invokeLater(() -> {
new ExtSynchro().setVisible(true);
});
}
class ExtClient extends Thread {
private volatile boolean bRunning;
@Override public void run() {
bRunning = true;
while (bRunning) {
try {
synchronized(oSignalExternal) {
try {
while (exConsumerServer.hasInteger()) {
pSrc.write(200);
try { Thread.sleep(3000); } catch (InterruptedException ex) { }
}
System.out.println(getClass().getName() + "\tsleeping");
oSignalExternal.wait();
} catch (InterruptedException e2) {}
if (!bRunning) break; // To exit from synchronized
}
} catch (IOException e) {
bRunning = false;
}
}
System.out.println(getClass().getName() + "\tfinishing");
}
public void stopThread() {
bRunning = false;
synchronized(oSignalExternal) {
oSignalExternal.notify();
}
}
};
//The Consumer Server.
class ExtServer extends Thread {
private volatile boolean bRunning;
//BlockingQueue<Integer> lConsumerClient =new ArrayBlockingQueue<>(10);
java.util.List<Integer> lConsumerClient = Collections.synchronizedList(new ArrayList<>(4));
@Override public void run() {
bRunning = true;
while (bRunning) {
int iRd;
try {
while ((iRd = pSnk.read()) != -1) {
for (int i = 0; i < lConsumerClient.size(); i++) {
int n = lConsumerClient.get(i);
System.out.println ("\t\ti:" + i + " ->" + n +"\t=" + (n + iRd));
}
}
} catch (IOException e) {}
}
System.out.println(getClass().getName() + "\tfinishing");
}
public void addInteger() {
new Thread (new Runnable() {
public void run() {
try {
System.out.println ("Add before size:" + lConsumerClient.size());
lConsumerClient.add((int)(Math.random()*100.0));
synchronized(oSignalExternal) {
oSignalExternal.notify();
}
System.out.println ("Add after size:" + lConsumerClient.size());
} catch (Exception e) { e.printStackTrace(); }
}
}).start();
}
public void removeFirst() {
new Thread (new Runnable() {
public void run() {
try {
System.out.println ("Remove before size:" + lConsumerClient.size());
if (hasInteger()) {
lConsumerClient.remove(0);
}
synchronized(oSignalExternal) {
oSignalExternal.notify();
}
System.out.println ("Remove after size:" + lConsumerClient.size());
} catch (Exception e) { e.printStackTrace(); }
}
}).start();
}
public boolean hasInteger() {
return lConsumerClient.size() > 0;
}
public void stopThread() {
bRunning = false;
try { pSrc.close();pSnk.close(); } catch (IOException e) {}
}
};
}
這是你期待我們閱讀的很多代碼。請把它剪下來[mcve]。 –
還有:「我是新手」,那麼遠離wait()和notify()。如果你知道自己在做什麼,你可以做出驚人的事情,但是它們很難正確使用。離開這些(實際上大多數多線程),直到你對Java更加紮實。 (我可以誠實地說,我不認爲我曾經需要使用這些實現:'java.util.concurrent'中的更高級別的類很容易正確使用。 –
有沒有一個主要的,什麼會剪切和粘貼完成? – matt