public class App3 {
public static void main(String[] args) {
Task task = new Task();
Thread t1 = new Thread(task);
Thread t2 = new Thread(task);
t1.start();
t2.start();
}
}
class Task implements Runnable{
private static AtomicInteger count = new AtomicInteger();
public Integer set(){
int number = count.incrementAndGet();//每次加1
System.out.println(number);
return number;
}
public void run() {
while(true){
Integer number = set();
if(count.getAndIncrement() > 200){
break;
}
}
}
}
AtomicInteger AtomicBoolean AtomicLong .....都是 java.util.concurrent.atomic 包下面的原子类
原子类是线程安全的,是用了CAS 无锁机制来保证线程的安全