Java Can';我不懂障碍代码
我遇到了这个障碍代码,无法理解Java Can';我不懂障碍代码,java,multithreading,barrier,Java,Multithreading,Barrier,我遇到了这个障碍代码,无法理解barrierPost方法 我应该用这段代码来解决一个练习,其中两组线程相互竞争数到10000 我不明白为什么相同的条件有相反的结果 public class Barrier { private int currentPosters = 0, totalPosters = 0; private int passedWaiters = 0, totalWaiters = 1; /** * @param totalPosters -
barrierPost
方法
我应该用这段代码来解决一个练习,其中两组线程相互竞争数到10000
我不明白为什么相同的条件有相反的结果
public class Barrier {
private int currentPosters = 0, totalPosters = 0;
private int passedWaiters = 0, totalWaiters = 1;
/**
* @param totalPosters - Nr of threads required to start the waiting threads
* @param totalWaiters - Nr of threads started later
*/
public Barrier (int totalPosters, int totalWaiters) {
this.totalPosters = totalPosters;
this.totalWaiters = totalWaiters;
}
public synchronized void init(int i) {
totalPosters = i; currentPosters=0;
}
public synchronized void barrierSet(int i) {
totalPosters = i; currentPosters=0;
}
public synchronized void barrierWait() {
boolean interrupted = false;
while (currentPosters = totalPosters) {
try {wait();}
catch (InterruptedException ie) {interrupted=true;}
}
passedWaiters++;
if (passedWaiters == totalWaiters) {
currentPosters = 0; passedWaiters = 0; notifyAll();
}
if (interrupted) Thread.currentThread().interrupt();
}
public synchronized void barrierPost() {
boolean interrupted = false; // In case a poster thread beats barrierWait, keep count of posters.
while (currentPosters == totalPosters) {
try {wait();}
catch (InterruptedException ie) {interrupted=true;}
}
currentPosters++;
if (currentPosters == totalPosters) notifyAll();
if (interrupted) Thread.currentThread().interrupt();
}
}
有人能帮忙吗?你能更详细地解释一下你所说的“我不明白为什么相同的条件有相反的不同结果”是什么意思吗?它不编译…
currentPosters=totalPosters
--将始终正确不,它不编译,因为结果不是布尔值(currentPosters=totalPosters){try{wait();}catch(InterruptedException ie){interrupted=true;}}}passedWaiters++;if(passedWaiters==totalWaiters){currentPosters=0;passedWaiters=0;notifyAll();