java8使用记录
2019-08-15 本文已影响0人
光小月
记录以下Java8 使用IntStream和 synchronized, executor的问题

代码
public class LockDemo {
volatile int count = 0;
synchronized void increment() {
count = count + 1;
}
void incrementSync() {
synchronized (this) {
count = count + 1;
}
}
private void testIncrement() throws Exception {
ExecutorService executor = Executors.newFixedThreadPool(2);
IntStream.range(0, 10000)
.forEach(i -> {
executor.submit(this::incrementSync);
});
// executor.awaitTermination(2L, TimeUnit.SECONDS);
executor.shutdown();
System.out.println(count); // 4238
}
public static void main(String[] args) throws Exception {
LockDemo lockDemo = new LockDemo();
lockDemo.testIncrement();
}
}
输出的结果是 4461
解答
是因为线程池任务执行中,主线程里shutdown了,所以没执行完。就打印到一部分
executor.shutdown() 不会阻塞 ,等待所有的完成
可以通过executor.isTerminated()
来判断
解答一: 成功 √
executor.awaitTermination(2L, TimeUnit.SECONDS);
/**
* Blocks until all tasks have completed execution after a shutdown
* request, or the timeout occurs, or the current thread is
* interrupted, whichever happens first.
*
* @param timeout the maximum time to wait
* @param unit the time unit of the timeout argument
* @return {@code true} if this executor terminated and
* {@code false} if the timeout elapsed before termination
* @throws InterruptedException if interrupted while waiting
*/
boolean awaitTermination(long timeout, TimeUnit unit)
throws InterruptedException;
解答二: 失败, ×
使用原子类 AtomcInteger,
PS: 若你觉得可以、还行、过得去、甚至不太差的话,可以“关注”一下,就此谢过!