【发布时间】:2019-09-10 03:24:04
【问题描述】:
我的第一个问题,感谢您的帮助! 我正在尝试使用两个线程交替打印奇数和偶数 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);
}
}
【问题讨论】:
-
查看文档:" 但是请注意,锁的公平性并不能保证线程调度的公平性。因此,使用公平锁的许多线程之一可能会连续多次获得它,而其他活动线程则没有进展并且当前没有持有锁。" docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/…
标签: java multithreading reentrantlock