我需要有人为我简化 java 中的等待通知方法。 我现在已经浏览了大约 200 个网站,但仍然不明白。
我正在开发一个程序,需要一个线程等待,直到从另一个线程调用通知...
class mainClass{
public static void main(String args[])throws Exception{
Thread t1 = new Thread(new Runnable(){
public void run(){
//code inside to make thread t1 wait untill some other thread
//calls notify on thread t1?
}
});
t1.start();
synchronized(t1){
//main thread calling wait on thread t1?
t1.wait();
}
new Thread(new Runnable(){
public void run(){
try{
synchronized(t1){
t1.notify() //?????
}
}catch(Exception e1){}
}
}).start();
}
}
最佳答案
等待需要在第一个 Runnable 中发生,并且您需要访问对象实例来等待,因此 t1 Thread 实例将无法工作。在此代码中,我创建了一个单独的锁对象。
public static void main(String[] args) {
final Object lock = new Object();
new Thread(new Runnable() {
@Override
public void run() {
synchronized(lock) {
try {
lock.wait();
System.out.println("lock released");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
System.out.println("before sleep");
try {
Thread.sleep(1000);
System.out.println("before notify");
synchronized(lock) {
lock.notify();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
使用线程通知可能很难测试。我建议使用基于消息的方法,例如 Akka .
关于java使用synchronized关键字的等待通知方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38426017/