Test:
package cn.eshore.dataCenter.test; public class Test2 { public static void main(String[] args) { Test3 test3=new Test3(); Thread t1 = new Thread(test3); t1.start(); Thread t2 = new Thread(test3); t2.start(); } }
Test3:
package cn.eshore.dataCenter.test; import java.util.concurrent.atomic.AtomicInteger; public class Test3 implements Runnable{ private static AtomicInteger count = new AtomicInteger(0); public void increase() { Thread th=Thread.currentThread(); //System.out.println("Tread name:"+th.getName()+",before:"+count); count.incrementAndGet(); System.out.println("Tread name:"+th.getName()+",after:"+count); } @Override public void run() { for(int i=0;i<5;i++) { this.increase(); } } }
结果:
Tread name:Thread-0,after:1 Tread name:Thread-1,after:2 Tread name:Thread-0,after:3 Tread name:Thread-0,after:5 Tread name:Thread-1,after:5 Tread name:Thread-1,after:7 Tread name:Thread-1,after:8 Tread name:Thread-1,after:9 Tread name:Thread-0,after:7 Tread name:Thread-0,after:10