package java_thread;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Created by zsm on 16-9-23.
*/
public class AtomicInte extends Thread{
final static AtomicInteger value = new AtomicInteger(0 );
final static int threadSize = 4;
static Integer in=0;
static void intThread1() throws InterruptedException {
Thread[] ts = new Thread[threadSize];
for (int i = 0; i < threadSize; i++) {
ts[i] = new Thread() {
@Override
public void run() {
for(int i=0;i<10110000;i++){
synchronized(""){
in++;
}
}
}
};
}
for (Thread t:ts) {
t.start();
}
for (Thread t:ts) {
t.join();
}//这个必须有
}
static void intThread2() throws InterruptedException {
Thread[] ts = new Thread[threadSize];
for (int i = 0; i < threadSize; i++) {
ts[i] = new Thread() {
@Override
public void run() {
for(int i=0;i<10110000;i++){
//value.addAndGet(1);
value.incrementAndGet();
}
}
};
}
for (Thread t:ts) {
t.start();
}
for (Thread t:ts) {
t.join();
}//这个必须有
}
public static void main(String[] args) throws InterruptedException {
AtomicInte at=new AtomicInte();
Long start=System.currentTimeMillis();
intThread2();
System.out.println("value: "+value);
Long start1=System.currentTimeMillis();
intThread1();
System.out.println("in: "+in);
Long end=System.currentTimeMillis();
System.out.println("AtomicInteger耗时:"+(start1-start));
System.out.println("syschronized耗时:"+(end-start1));
}
}
value: 40440000
in: 40440000
AtomicInteger耗时:2509
syschronized耗时:4135