加法多线程
我有两个文件:AddThread.java进行加法操作。Core.java是主线程文件。得到的结果sum = 10. 可是我觉得应该得到20才对呀。
package Threads;public class AddThread implements Runnable{ private volatile static int sum = 0; public AddThread(){ } public void run(){ { for(int i = 0;i<10;++i){ int temp = sum; temp = temp +1; try{ Thread.sleep(20); }catch(InterruptedException e){ System.out.println(e); } sum = temp; System.out.println("This sum is "+ sum); } } } public static int getSum(){ return sum; }}package Threads;public class Core { public static void main(String[] args){ AddThread first = new AddThread(); AddThread second = new AddThread(); Thread one = new Thread(first); Thread two = new Thread(second); one.setName("firstThread"); two.setName("secondThread"); one.start(); two.start(); while(one.isAlive()||two.isAlive()){ } System.out.println(AddThread.getSum()); }}