0

我有 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 位于缓存内存中,然后通过线程修改此值,第二个线程不会看到?

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

4

1 回答 1

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
于 2012-07-30T08:48:29.660 回答