我在synchronzed(myThread)块中有myThread.wait()。我有实现runnable的Myrunner。我想要区分notify()和myRunner,但它不是监视器对象。是否可以从myRunnable获取myThread的句柄以进行通知?有没有其他的解决方案?从Thread扩展myRunnable并运行它并不好,原因与我的代码相关。
public class ThreadMain {
public Thread reader;
private class SerialReader implements Runnable {
public void run() {
while (true) {
try {
Thread.sleep(3000);
synchronized(this) {
System.out.println("notifying");
notify();
System.out.println("notifying done");
}
} catch (Exception e) {
System.out.println(e);
}
}
}
}
ThreadMain() {
reader = new Thread(new SerialReader());
}
public static void main(String [] args) {
ThreadMain d= new ThreadMain();
d.reader.start();
synchronized(d.reader) {
try {
d.reader.wait();
System.out.println("got notify");
} catch (Exception e) {
System.out.println(e);
}
}
}
}发布于 2013-08-01 14:08:21
要notify()一个wait()线程,你有很多对它的wait()所在对象的引用,并且你必须能够获得它的锁。我建议你也改变一个通知的状态,当wait()ing时,你在一个循环中检查这个状态的改变。
唯一的另一个选择是更改等待线程的代码。
发布于 2013-08-01 14:19:14
两个线程应该使用相同的对象进行同步。此外,您实际上不应该使用现有的对象来同步,而应该创建一个显式用于同步的对象,例如
Object lock = new Object();如果锁用于与线程交互,您可以将它放在线程中,并提供一个getter供任何人使用。
https://stackoverflow.com/questions/17986301
复制相似问题