java中的交替同步非同步块
我有一个关于同步块和多线程的问题。我有一种“交替”的情况,在这种情况下,两个同步块应该在非同步块之前和之后执行,并且这些块不应该相互干扰 以下是(部分)代码:java中的交替同步非同步块,java,multithreading,synchronization,Java,Multithreading,Synchronization,我有一个关于同步块和多线程的问题。我有一种“交替”的情况,在这种情况下,两个同步块应该在非同步块之前和之后执行,并且这些块不应该相互干扰 以下是(部分)代码: boolean calculate = false; synchronized(this){ Double oldSim = struct.get(pair); if(oldSim == null || oldSim < maxThreshold) calculate = true; }
boolean calculate = false;
synchronized(this){
Double oldSim = struct.get(pair);
if(oldSim == null || oldSim < maxThreshold)
calculate = true;
}
if(calculate)
{
// This part should be parallel
Double newSim = calculateSimilarity(...);
synchronized(this){
if(newSim > minThreshold && (oldSim == null || newSim > oldSim))
struct.put(pair, newSim);
}
}
布尔计算=false;
已同步(此){
Double oldSim=结构获取(成对);
如果(oldSim==null | | oldSimminThreshold&(oldSim==null | | newSim>oldSim))
结构put(pair,newSim);
}
}
问题在于,通过这种方式,不同的线程可以执行第一个同步块,而另一个线程可以执行第二个同步块。因此,我认为这个解决方案:
int maxThreshold = 1.0;
if(checkAndwriteSimilarity(pair, null, false))
{
Double newSim = calculateSimilarity(table, pKey1, pKey2, pKey1Val, pKey2Val, c);
checkAndwriteSimilarity(pair, newSim, true);
}
private synchronized boolean checkAndwriteSimilarity(Pair pair, Double newSim, boolean write)
{
Double oldSim = struct.get(pair);
if(!write)
{
if(oldSim == null || oldSim < maxThreshold)
return true;
else
return false;
}
else
{
if(newSim > minThreshold && (oldSim == null || newSim > oldSim))
struct.put(pair, newSim);
return true;
}
}
intmaxthreshold=1.0;
if(检查和写入相似性(对、空、假))
{
Double newSim=计算相似性(表,pKey1,pKey2,pKey1Val,pKey2Val,c);
检查和写入相似性(配对、新闻IM、真);
}
专用同步布尔校验和写入相似性(对对、双新闻IM、布尔写入)
{
Double oldSim=结构获取(成对);
如果(!写入)
{
如果(oldSim==null | | oldSimminThreshold&(oldSim==null | | newSim>oldSim))
结构put(pair,newSim);
返回true;
}
}
你认为这是最正确的解决办法吗?我真的不太喜欢这种方法。。。
你有其他的解决方案可以建议吗
谢谢如果你想并行运行计算,我觉得这是合理的。你可能已经更新了密钥。不要使用
synchronized(这个)
我什么都不做,因为每个线程都是自己的同步对象。你说的“不同的线程可以执行…而另一个线程可以执行”是什么意思?在特定对象上,任何时候只能有一个同步的块处于活动状态;多个不同的synchronized
块不会并行运行。因此,您希望确保一个线程进入第一个同步块,然后同一个线程进入第二个同步块,即使其他线程现在进入第一个块也可以吗?什么样的疯狂决定了这个需求?我使用Runnable接口,所以只有一个对象。如果chrylis是正确的,那么我应该不会在不同的同步块之间有任何干扰。