我在完成主线程时遇到问题。线程“完成”(可能不是,我不知道,但我在静态变量“nextNumber”中有正确的结果),程序仍然有效。
我认为Executor没有终止,因为他仍然在等待另一个线程运行。
之前我使用过自己的runnable类,并且没有注意终止它。
我的代码:
private static long nextNumber = 0;
public static void main(String[] args) {
Runnable firstCounter = () -> {
for (int i = 0; i < 1000000; i++)
increment("Thread 1");
};
Runnable secondCounter = () -> {
for (int i = 0; i < 1000000; i++)
increment("Thread 2");
};
Executor executor = Executors.newFixedThreadPool(2);
executor.execute(firstCounter);
executor.execute(secondCounter);
System.out.println(nextNumber);
}
synchronized private static void increment(String threadName) {
System.out.println(threadName + " " + ++nextNumber);
}
首先你需要使用ExecutorService
然后你需要关闭它。
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.shutdown(); //Prevents executor from accepting new tasks
executor.awaitTermination(Integer.MAX_VALUE, TimeUnit.SECONDS); //Waits until currently executing tasks finish but waits not more then specified amount of time