线程同步 [英] Thread Synchronization
问题描述
我的程序中有2个线程,如下所示:
I have 2 threads in my program as follows:
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
语句.
In the second thread, the Boolean
CONNECTION_ESTABLISHED
is set to true
at a certain point. If I don't use Thread.sleep(1000)
in the 1st thread, after CONNECTION_ESTABLISHED
is set to true
in the 2nd thread I don't enter the relevant if
statement in the 1st thread.
还有其他解决方法吗?因为我的第一个线程通常依赖于第二个线程中的变量更改.
Is there another way around this? Because my 1st thread will often be dependent on variable changes in the second thread.
推荐答案
将volatile
关键字添加到CONNECTION_ESTABLISHED
方法中,然后查看.
Add volatile
keyword to the CONNECTION_ESTABLISHED
method and see.
这篇关于线程同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!