这个java应用程序将启动三个线程并倒数一个数字。一旦计数器达到零,线程将完成并退出。不幸的是,计数器将绕过零检查。怎么解决?
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ThreadTest {
volatile Long totalMsg = 100L;
final Lock maxLimitLock = new ReentrantLock();
public void start() {
int threadNumber = 3;
ExecutorService executor = Executors.newFixedThreadPool(threadNumber);
for (int i = 0; i < threadNumber; i++) {
executor.submit(new ThreadTest.ConsumerThread(i));
}
}
class ConsumerThread implements Runnable {
private int threadNumber;
public ConsumerThread(int threadNumber) {
this.threadNumber = threadNumber;
}
public void run() {
while (true) {
try {
maxLimitLock.lock();
totalMsg--;
System.out.println(totalMsg + " left");
if (totalMsg == 0) {
System.out.println("finished all of " + totalMsg);
break;
}
} finally {
maxLimitLock.unlock();
}
}
System.out.println("thread " + this.threadNumber + " finished");
}
}
public static void main(String[] args) throws Exception {
ThreadTest reader = new ThreadTest();
reader.start();
}
}
感谢。
答案 0 :(得分:1)
代码中的问题在这里
totalMsg--;
...
if (totalMsg == 0) {
您的代码总是递减计数器,以便只能释放一个线程,后续线程将具有一个计数器&lt; 0因此它们永远不会被释放,所以你应该用
替换它if (totalMsg <= 0) {
或
if (totalMsg > 0) {
totalMsg--;
System.out.println(totalMsg + " left");
} else {
System.out.println("finished all of " + totalMsg);
break;
}
注意:考虑使用AtomicLong
作为您的计数器。