游戏开发

JAVA并发编程学习--AtomicInteger

2016-12-05  本文已影响22人  higher2017

源代码:

import java.util.concurrent.atomic.AtomicInteger;

class MyThread implements Runnable {
  static AtomicInteger ai = new AtomicInteger(0);
  public void run() {
    for (int m = 0; m < 100000; m++) {
     ai.getAndIncrement();
    }
  }
}

class MyThread1 implements Runnable {
  static Integer ai = new Integer(0);
  public void run() {
  //如果出现多个线程同时执行下面的for循环将会出现执行完m++就跳转到另一个  线程然后又跳转到另一线程执行到m++
  //这样ai就只加了1,而m却加了2,这样ai最终的值就会小于100000*n(n为执行  该段代码的线程数)
    for (int m = 0; m < 100000; m++) {
      ai++;
    }
  }
}

class MyThread2 implements Runnable {
  static Integer ai = new Integer(0);
   public void run() {
  //线程安全
  synchronized (MyThread2.class) {
    for (int m = 0; m < 100000; m++) {
      ai++;
    }
  }
}
}

/**
* AtomicInteger其实就是Integer,但是它是线程安全的
*
* @author JM
* @date 2016-12-4 下午11:22:39
* @since JDK 1.7
*/
public class AtomicIntegerTest {
   public static void main(String[] args) throws InterruptedException {
    MyThread mt = new MyThread();
    MyThread1 mt1 = new MyThread1();
    MyThread2 mt2 = new MyThread2();
    Thread t1 = new Thread(mt);
    Thread t2 = new Thread(mt);
    Thread t11 = new Thread(mt1);
    Thread t12 = new Thread(mt1);
    Thread t21 = new Thread(mt2);
    Thread t22 = new Thread(mt2);
    t1.start();
    t2.start();
    Thread.sleep(500);
    t11.start();
    t12.start();
    Thread.sleep(500);
    t21.start();
    t22.start();
    Thread.sleep(500);
    System.out.println("AtomicInteger线程安全得到的结果:"+MyThread.ai.get());
    System.out.println("普通的i++操作,线程不安全的结果:"+MyThread1.ai);
    System.out.println("加了synchronized,保证线程安全"+MyThread2.ai);
    //该行代码表示AtomicInteger其实就是Integer(int)只不过是线程安全的int
    int e = MyThread.ai.get();
    System.out.println("AtomicInteger转换为int的结果:"+e);
  }
}

以上代码为了展示AtomicInterger其实就是int;和线程安全的特性。其中举了MyThread1(普通线程)和MyThread2(线程安全线程)两个例子来举例说明

MyEclipse执行结果

上一篇 下一篇

猜你喜欢

热点阅读