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也没有继续执行...请各位高手帮忙解决...
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也没有继续执行...请各位高手帮忙解决...
TestThread tt = new TestThread(2);你用的是不同的锁