Java [android]:我应该使用synchronized ou信号量对象吗?

时间:2012-07-30 08:44:03

标签: java android multithreading

我有2个帖子。

第一个调用此函数

public int doCompute1(obj)
{
    if (obj.state == OK_FOR_COMPUTE1)
    {
      // do something
      obj.state = OK_FOR_COMPUTE2;
    }
}

第二个线程调用此函数

public int doCompute2(obj)
{
    if (obj.state == OK_FOR_COMPUTE2)
    {
      // do something
      obj.state = OK_FOR_COMPUTE1;
    }
}

目前它看似完美无缺!

我的问题是:这是正确的吗? 是否有可能在多核处理器上,obj.state在高速缓冲存储器中然后通过线程修改这个vaue,第二个线程是不可见的?

如果此代码不正确,该怎么办?

1 个答案:

答案 0 :(得分:2)

synchronized(obj){  
    if (...){ 
    }
}

会做的事情

编辑:

同步做什么?

synchronized(obj){  //if obj is not locked,i lock it and go to the if instruction.if obj is locked, i'm waiting for its unlocking

          //some stuff that will run with no thread-interruption caused by other synchronized block locked on the obj object 

    }//the obj object is unlocked and let other methods enter their synchronized(obj) block