情况是这样的,我发一个请求出去必需要等待应答回来,但是应答是异步的,请求是一个线程在执行,在等待应答前先等待,可以执行Thread.join(60)比如超时时间是60妙,并将该线程的信息放在一个全局变量中(比如map<String, "返回结果">)。当有应答回来的时候,是另一个线程接收的,它根据map中的KEY设置全局变量中的相应的“返回结果”value值。然后通知那个线程继续运行,就是有返回结果了,你可以继续操作了。能实现这样的效果吗?我看API中好像不能通过一个线程去唤醒另一个线程。不知道有没有别的办法?
如果线程a在某对象上wait,肯定是其它线程来调用这个对象的notify/All来唤醒线程。线程a执行 wait,可以直接是wait(),也就是在线程自己的对象上wait.
然后线程b通过a.notify来唤醒a
当然a可以在b上wait,那么b可以直接调用自己的notify来唤醒a.a也可以在其它对象上wait,然后b通过这个对象的notify来唤醒a.
public class Test{
public static void main(String [] args){
Map<String,Integer> map =new HashMap<String,Integer>();
ThreadRead tr1=new ThreadRead(map);
ThreadWrite tw1=new ThreadWrite(map);
tr1.start();
tw1.start();
}
}
class ThreadRead extends Thread{
private Map<String,Integer> map=null;
public ThreadRead(Map<String,Integer> map) {
this.map=map;
}
@Override
public void run() {
super.run();
synchronized(map){
try{
while(map.get("ok")==null){
map.wait();
}
System.out.println(map.get("ok"));
}catch(Exception e){
} }
}
}
class ThreadWrite extends Thread{
private Map<String,Integer> map=null;
public ThreadWrite(Map<String,Integer> map) {
this.map=map;
}
@Override
public void run() {
super.run();
synchronized(map){
try{
map.put("ok", 10000);
}catch(Exception e){
} }
}
}
然后A要等B,则synchronized {
...
syncObject.wait();
...
}在B中只要调用synchronized {
syncObject.notify();
}非常之简单
经典有杀手型程序
既然Read在等待map.get("ok")!=null,那么put的线程就必须 notify,否则就是一个致命的设计性错误。
非常之简单,也是非常之错误!
不是A要B等,也不是A等B,而是A在等待时停靠的是syncObject。B(或其它线线程)都可以让A离开syncObject
的等待停靠点开然后开始运行。而绝对不是A让B进行等待。
public class Test{
public static void main(String [] args){
Map<String,Integer> map =new HashMap<String,Integer>();
ThreadRead tr1=new ThreadRead(map);
ThreadWrite tw1=new ThreadWrite(map);
tr1.start();
tw1.start();
}
}
class ThreadRead extends Thread{
private Map<String,Integer> map=null;
public ThreadRead(Map<String,Integer> map) {
this.map=map;
}
@Override
public void run() {
super.run();
synchronized(map){
try{
System.out.println("ooooooooooooooooo");
while(map.get("ok")==null){
map.wait();
}
System.out.println(map.get("ok"));
}catch(Exception e){
} }
}
}
class ThreadWrite extends Thread{
private Map<String,Integer> map=null;
public ThreadWrite(Map<String,Integer> map) {
this.map=map;
}
@Override
public void run() {
super.run();
synchronized(map){
try{
map.put("ok", 10000);
map.notifyAll();
}catch(Exception e){
} }
}
}漏掉,加上。最好还是用notifyAll()。