public class ConnectThread extends Thread { Object lock; public ConnectThread(int a) {
lock = a;
}
private boolean flag = true; public void run() {
while (flag) {
synchronized (lock) {
try {

//此处比如 连接某种数据库... 标记1
lock.notify();  //通知  -> 唤醒线程 setFlag(false);    // 连接成功 flag=false 线程终止
} catch (AppException e) {
setFlag(true);
e.printStackTrace();
}
System.out.println("ConnectThread " + flag);
try {
sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public boolean getFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
}
public class TestThread extends Thread {
Object lock; public TestThread(int a) {
lock = a;
} public void run() {
while (true) {
synchronized (lock) {
try {
//此处比如 连接某种数据库... 标记2
} catch (AppException e1) {

ConnectThread ct = new ConnectThread(1);
ct.start();
if (ct.getFlag()) {
System.out.println("连接失败");
try {
System.out.println("waiting...");
lock.wait();
System.out.println("waiting...");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
try {
sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(" TestThread  " + this.isAlive());
}
}
} public static void main(String[] args) {
TestThread tt = new TestThread(2);
tt.start();
}执行(比如连接某种数据库或其他连接操作,代码中的标记1和标记2相同),如果在TestThread中连接失败,抛出异常,将此线程等待,开启辅助线程ConnectThread继续执行连接操作,如果连接成功将辅助线程ConnectThread关闭,此时在辅助线程ConnectThread将TestThread唤醒(notify),但是唤醒没有效果啊,TestThread也没有继续执行...请各位高手帮忙解决...

解决方案 »

  1.   

    int怎可以放到object,传递的不是引用
      

  2.   

    ConnectThread ct = new ConnectThread(1);
    TestThread tt = new TestThread(2);你用的是不同的锁
      

  3.   

    即使传 同样的int值也是不同的object, 即使是auto box把int 转成Integer ,也应该是生成不同的对象。建议楼主不要使用 Integer对象作为 lock object,因为 Integer 是 final value的,一旦值发生改变,对象就变了。其他的没细看,楼主把你的观点和问题先摆出来。