在打印线程计数时,线程尚未完成执行。
为了演示,
Thread.sleep()在打印出线程数之前添加一条指令:
public class App { private int count = 0; public static void main(String[] args) throws InterruptedException { App app = new App(); app.doWork(); } public void doWork() throws InterruptedException { Thread t1 = new Thread(new Runnable() { public void run() { for (int i = 0; i < 10000; i++) { count++; } } }); Thread t2 = new Thread(new Runnable() { public void run() { for (int i = 0; i < 10000; i++) { count++; } } }); t1.start(); t2.start(); Thread.sleep(5000); System.out.println("Count is: " + count); // Count is: 20000 }}
还要注意,对基元的 *** 作不是线程安全的,并且该
count++*** 作也不是原子的。您应该同步访问
count变量,或使用
AtomicInteger或
LongAdder代替
int。就目前而言,最终的计数可能在零到20,000之间。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)