1000个线程进行 +1 操作(AtomicInteger、CountDownLatch)

1000个线程进行 +1 操作,如何保证线程安全得到正确的1000?

  • AtomicInteger 保证操作的原子性,解决了线程安全的问题。
  • CountDownLatch 保证各个线程都执行完成后,再输出最后的结果,避免输出中间的结果。
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

public class 线程2 {
    static AtomicInteger count = new AtomicInteger(0);
    static CountDownLatch cdl = new CountDownLatch(1000);

    public static void main(String[] args) throws InterruptedException {
        CountRunnable countRunnable = new CountRunnable();
        for (int i = 0; i < 1000; i++) {
            new Thread(countRunnable).start();
        }
        cdl.await();
        System.out.println(count);
    }

    public static class CountRunnable implements Runnable {

        @Override
        public void run() {
            count.getAndIncrement();
            cdl.countDown();
        }
    }
}

1000个线程进行 +1 操作,各操作1000次,如何保证线程安全得到正确的 1000000?

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

public class 线程 {
    static AtomicInteger count = new AtomicInteger(0);
    static CountDownLatch cdl = new CountDownLatch(1000);

    public static void main(String[] args) throws InterruptedException {
        CountRunnable countRunnable = new CountRunnable();
        for (int i = 0; i < 1000; i++) {
            new Thread(countRunnable).start();
        }
        cdl.await();
        System.out.println(count);
    }

    public static class CountRunnable implements Runnable {

        @Override
        public void run() {
            for (int i = 0; i < 1000; i++) {
                count.getAndIncrement();
            }
            cdl.countDown();
        }
    }
}

你可能感兴趣的:(06,并发多线程)