同步我采取的是计算Julia集的程序。它将使用多个线程,具体取决于可用的处理器数量。每个线程计算一条线,但只有当该线不被另一个线程计算时。这部分工作得很好。多线程安全在Java
但有时,当我测试它与更大的图像(更多的线来计算,例如而不是getHeight() = 1200
,我把它设置为3000
,有一些行被跳过)。我想让它更安全,这样不会有两行计算,也不会跳过任何行。这里是run()
方法的代码:我希望它这样的工作
public void run() {
while (counter < getHeight()-1) {
synchronized(this) {
if (counter >= getHeight() -1) { //so that the last line will not be calculated >2 times.
return;
}
counter++;
image.setRGB(0, counter, getWidth(), 1, renderLine(counter), 0, 0);
}
}
}
:如果所计算的当前行,线程便进入到下一行..不,它感到困惑,使线得到跳过..
我想这其实:
public void run() {
while (counter < getHeight()-1 && !working) {
synchronized(this) {
working = true;
if (counter >= getHeight() -1) { //so that the last line will not be calculated >2 times.
return;
}
counter++;
image.setRGB(0, counter, getWidth(), 1, renderLine(counter), 0, 0);
working = false;
}
}
}
,但是,我不知道这是否会阻止访问到另一个线程当某个线程已经工作,它将改变值“counter”,这意味着行可以跳过!
我需要一个布尔变量来通知线程实际工作的一条线吗?有什么建议?
的方法
run
u可以有一个数组表示已经获得的线的数量。但如果线数增加,肯定会使应用程序变慢。 – Asif