日期:2014-05-20 浏览次数:20739 次
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()); } }