线程同步 [英] Thread Synchronization

查看:65
本文介绍了线程同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的程序中有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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆