截图说明:
AtomicInteger 是原子操作类,适用于多线程更新变量的操作。
// 没有使用线程池测试代码:
public class JVMThreadTest extends Thread{
private static final AtomicInteger count = new AtomicInteger(); // Atomic operation class
public static void main(String[] args) {
while (true){
new JVMThreadTest().start();
}
}
@Override
public void run() {
System.out.println(count.incrementAndGet());
while (true){
try {
Thread.sleep(Integer.MAX_VALUE);
} catch (InterruptedException e) {
break;
}
}
}
}
// 使用线程池的测试代码
public class JVMThreadTest2 implements Runnable{
private static final AtomicInteger count = new AtomicInteger(); // Atomic operation class
private static ExecutorService executorService = Executors.newCachedThreadPool();
public static void main(String[] args) {
while (true){
executorService.execute(new JVMThreadTest2());
}
}
@Override
public void run() {
System.out.println(count.incrementAndGet());
while (true){
try {
Thread.sleep(Integer.MAX_VALUE);
} catch (InterruptedException e) {
break;
}
}
}
}