我需要有人为我简化Java中的wait notify方法。我已经查看了大约200多个站点,但仍然不了解。
我正在一个需要一个线程等待直到从另一个线程调用notify的程序上...
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中发生,并且您需要有权访问Object实例才能等待,因此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这样的基于消息的方法。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句