我的程序中有 2 个线程,如下所示:
class SendThread implements Runnable {
public void run(){
Thread.sleep(1000);
while (true){
if (CONNECTION_ESTABLISHED){
// code here
}
}
}
}
class ReceiveThread implements Runnable {
public void run(){
while (true){
// code here
CONNECTION_ESTABLISHED = true;
}
}
}
我已经定义CONNECTION_ESTABLISHED为static Boolean.
在第二个线程中,Boolean CONNECTION_ESTABLISHED设置为true某个点。如果我不在第一个线程中使用Thread.sleep(1000),在第二个线程CONNECTION_ESTABLISHED中设置为之后true我不会在第一个线程中输入相关if语句。
还有其他方法吗?因为我的第一个线程通常会依赖于第二个线程中的变量变化。