我的第一个问题,感谢您的帮助! 我正在尝试使用两个线程交替打印奇数和偶数 1~100。 预期结果:
pool-1-thread-1=> 1
pool-1-thread-2=> 2
pool-1-thread-1=> 3
pool-1-thread-2=> 4
......
pool-1-thread-1=> 99
pool-1-thread-2=> 100
我想我可以使用FairSync,但它只能保证大部分打印是正确的。像这样:
pool-1-thread-1=> 55
pool-1-thread-2=> 56
pool-1-thread-1=> 57
pool-1-thread-2=> 58
pool-1-thread-2=> 59 //※error print※
pool-1-thread-1=> 60
pool-1-thread-2=> 61
pool-1-thread-1=> 62
不知道为什么极少数情况下会丢单? 你可以批评我的代码和我的英语。 这是我的代码:
private static final int COUNT = 100;
private static final int THREAD_COUNT = 2;
private static int curr = 1;
static ReentrantLock lock = new ReentrantLock(true);
static ExecutorService executorService = Executors.newCachedThreadPool();
public static void main(String[] args) {
Runnable task = () -> {
for (; ; ) {
try {
lock.lock();
if (curr <= COUNT) {
System.out.println(Thread.currentThread().getName() + "=> " + curr++);
} else {
System.exit(0);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
};
for (int i = 0; i < THREAD_COUNT; i++) {
executorService.execute(task);
}
}
最佳答案
不,亲爱的,您的实现不正确。哪个线程获得运行的机会由操作系统决定。无法保证线程 1 和 2 会依次执行。
您可以通过检查变量 curr 的先前值来修复您的代码,如果该值不是该线程期望的值,则不要递增和打印。
例如:
if(curr.threadName.equals("Thread 2") && (curr%2 !=0))
{
// Print
// Increment
}
关于java - FairSync 能保证执行顺序吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57863639/