姚博文 使用synchronized同步和用Atomic的差别

来源:互联网 发布:网络柜电气设计 编辑:程序博客网 时间:2024/05/17 10:52

测试使用synchronized同步和AtomicInteger的差别:
public class TestSynchronized {

 private int count1 = 0;

 public synchronized void addCount1() {
  count1++;
 }

 public synchronized int getCount1() {
  return count1;
 }

 /**
  * @param args
  */
 public static void main(String[] args) {
  Thread[] t = new Thread[10];
  TestSynchronized a = new TestSynchronized();
  for (int i = 0; i < t.length; i++) {
   t[i] = new Thread1(a);
  }
  long start = System.currentTimeMillis();
  for (int i = 0; i < t.length; i++) {
   t[i].start();
  }
  while (true) {
   boolean over = true;
   for (int i = 0; i < t.length; i++) {
    if (t[i].isAlive()) {
     over = false;
     break;
    }
   }
   if (over) {
    break;
   }
  }
  long end = System.currentTimeMillis();
  System.out.println(end - start);
 }

 static class Thread1 extends Thread {

  private TestSynchronized a;

  public Thread1(TestSynchronized a) {
   this.a = a;
  }

  @Override
  public void run() {
   for (int i = 0; i < 100000; i++) {
    a.addCount1();
    if (a.getCount1() == 1000000000) {
     break;
    }
   }
  }
 }
}
执行时间8422ms
public class TestAtomic {

 private AtomicInteger count1 = new AtomicInteger();

 public void addCount1() {
  count1.addAndGet(1);
 }

 public int getCount1() {
  return count1.get();
 }

 /**
  * @param args
  */
 public static void main(String[] args) {
  Thread[] t = new Thread[10];
  TestAtomic a = new TestAtomic();
  for (int i = 0; i < t.length; i++) {
   t[i] = new Thread2(a);
  }
  long start = System.currentTimeMillis();
  for (int i = 0; i < t.length; i++) {
   t[i].start();
  }
  while (true) {
   boolean over = true;
   for (int i = 0; i < t.length; i++) {
    if (t[i].isAlive()) {
     over = false;
     break;
    }
   }
   if (over) {
    break;
   }
  }
  long end = System.currentTimeMillis();
  System.out.println(end - start);
 }

 static class Thread2 extends Thread {

  private TestAtomic a;

  public Thread2(TestAtomic a) {
   this.a = a;
  }

  @Override
  public void run() {
   for (int i = 0; i < 100000; i++) {
    a.addCount1();
    if (a.getCount1() == 1000000000) {
     break;
    }
   }
  }
 }
}
执行时间125ms
这个就是差距.因为Atomic采用的是机器级别的原子指令,在硬件实现 

原创粉丝点击