我想要做的是讓一個線程將它從父線程接收到的消息寫入一個OutputStream,監聽一個InputStream的回覆,然後通過回覆通知父線程。我寫了兩個測試類,它們以不同的方式做類似但更簡單的測試。 方法1僅在"before loop"
調試語句未註釋時才起作用,方法2僅打印"message from child"
調試語句。我究竟做錯了什麼?線程間消息傳遞的實現
方法1
public class Parent {
private static int out = 0;
private static int in = 0;
public static void main(String[] args) {
final Object locker = new Object();
Thread t = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
synchronized (locker) {
try {
locker.wait();
System.out.println("Message from parent " + out);
in = out + 10;
locker.notify();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
});
t.start();
System.out.println("before loop");
while (out < 10) {
synchronized (locker) {
locker.notify();
try {
locker.wait();
out++;
System.out.println("Message from child " + in);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
方法2
public class Parent {
/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
final BlockingQueue<Integer> q = new ArrayBlockingQueue<Integer>(1);
Thread t = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Integer i = q.take();
System.out.println("Message from parent: " + i.intValue());
q.put(i.intValue() + 10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
for (int i = 0; i < 10; i++) {
q.put(i);
Integer j = q.take();
System.out.println("Message from child: " + j);
}
}
}
不是真的,我只是不太瞭解java :-)謝謝! – Johnny 2012-04-15 15:10:52