<span style="font-family: Arial, Helvetica, sans-serif;">package com.jdk5.thread.AtomicInteger;</span>
import java.util.concurrent.atomic.AtomicInteger;
/**
* Created by Vincent on 2014/8/6.
*/
public class Demo1 {
public static void main(String[] args) throws InterruptedException {
SameDemo sameDemo = new SameDemo();
System.out.println(sameDemo.getI());
long time1 = System.currentTimeMillis();
Thread t1 = new Thread(new Thread1(sameDemo));
Thread t2 = new Thread(new Thread2(sameDemo));
t1.start();
t2.start();
t1.join();
t2.join();
long time2 = System.currentTimeMillis();
System.out.println(time2-time1);
System.out.println(sameDemo.getI());
}
}
class SameDemo {
private int i = 1000;
public int getI() {
return i;
}
public void setI(int i) {
this.i=i;
}
public void add() {
i+=1;
}
public void dec() {
i-=1;
}
}
class Thread1 implements Runnable {
private SameDemo sameDemo;
Thread1(SameDemo sameDemo) {
this.sameDemo = sameDemo;
}
@Override
public void run() {
for (int i = 0; i < 100000000; i++) {
sameDemo.add();
}
}
}
class Thread2 implements Runnable {
private SameDemo sameDemo;
Thread2(SameDemo sameDemo) {
this.sameDemo = sameDemo;
}
@Override
public void run() {
for (int i = 0; i < 100000000; i++) {
sameDemo.dec();
}
}
}
package com.jdk5.thread.AtomicInteger;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Created by Vincent on 2014/8/6.
*/
public class Demo1 {
public static void main(String[] args) throws InterruptedException {
SameDemo sameDemo = new SameDemo();
System.out.println(sameDemo.getI());
long time1 = System.currentTimeMillis();
Thread t1 = new Thread(new Thread1(sameDemo));
Thread t2 = new Thread(new Thread2(sameDemo));
t1.start();
t2.start();
t1.join();
t2.join();
long time2 = System.currentTimeMillis();
System.out.println(time2-time1);
System.out.println(sameDemo.getI());
}
}
class SameDemo {
private AtomicInteger i = new AtomicInteger(1000);
public int getI() {
return i.get();
}
public void setI(int i) {
this.i.set(i);
}
public void add() {
this.i.incrementAndGet();
}
public void dec() {
this.i.decrementAndGet();
}
}
class Thread1 implements Runnable {
private SameDemo sameDemo;
Thread1(SameDemo sameDemo) {
this.sameDemo = sameDemo;
}
@Override
public void run() {
for (int i = 0; i < 100000000; i++) {
sameDemo.add();
}
}
}
class Thread2 implements Runnable {
private SameDemo sameDemo;
Thread2(SameDemo sameDemo) {
this.sameDemo = sameDemo;
}
@Override
public void run() {
for (int i = 0; i < 100000000; i++) {
sameDemo.dec();
}
}
}
AtomicInteger平均时间8500ms左右,纯粹的int大约8ms左右,也就是说AtomicInteger虽然保证了线程安全,但效率低了1000倍之多