当前位置: 代码迷 >> 综合 >> 009.多线程-AtomicInteger
  详细解决方案

009.多线程-AtomicInteger

热度:76   发布时间:2023-12-14 05:00:36.0
package cn.qbz.thread;import java.util.concurrent.atomic.AtomicInteger;public class AtomicTest {
    public static void main(String[] args) {
    AtomicInteger count = new AtomicInteger(0);//分10个线程,每个线程自增2000次for (int i = 0; i < 10; i++) {
    new Thread(new ThreadTest1(count)).start();}try {
    Thread.sleep(1000);} catch (InterruptedException e) {
    e.printStackTrace();}System.out.println(count.get());}
}class ThreadTest1 implements Runnable {
    private AtomicInteger integer;ThreadTest1(AtomicInteger integer) {
    this.integer = integer;}public void run() {
    for (int i = 0; i < 2000; i++) {
    integer.incrementAndGet();}}
}


此时的数值会小于20000

package cn.qbz.thread;public class AtomicTest {
    //静态变量可为多线程共享private static Integer count = 0;public static void main(String[] args) {
    //分10个线程,每个线程自增2000次for (int i = 0; i < 10; i++) {
    new Thread(new Runnable() {
    public void run() {
    for (int i = 0; i < 2000; i++) {
    count++;}}}).start();}try {
    Thread.sleep(1000);} catch (InterruptedException e) {
    e.printStackTrace();}System.out.println(count);}
}

如上面一样,使用AtomicInteger

package cn.qbz.thread;import java.util.concurrent.atomic.AtomicInteger;public class AtomicTest {
    public static void main(String[] args) {
    final AtomicInteger count = new AtomicInteger(0);//分10个线程,每个线程自增2000次for (int i = 0; i < 10; i++) {
    new Thread(new Runnable() {
    public void run() {
    for (int i = 0; i < 2000; i++) {
    count.incrementAndGet();}}}).start();}try {
    Thread.sleep(1000);} catch (InterruptedException e) {
    e.printStackTrace();}System.out.println(count.get());}
}

其他的Atomic类与此类似