多線程累加計數

使用Runnable接口

public class ThreadTest {

    // 公共變量
    int count = 0;

    public static void main(String[] args) {
        ThreadTest threadTest = new ThreadTest();

        MyRunnable myRunnable = threadTest.new MyRunnable();
        MyRunnable myRunnable1 = threadTest.new MyRunnable();
        MyRunnable myRunnable2 = threadTest.new MyRunnable();
        MyRunnable myRunnable3 = threadTest.new MyRunnable();
        MyRunnable myRunnable4 = threadTest.new MyRunnable();

        new Thread(myRunnable).start();
        new Thread(myRunnable1).start();
        new Thread(myRunnable2).start();
        new Thread(myRunnable3).start();
        new Thread(myRunnable4).start();
    }

    /**
     * 創建一個實現Runnable的類
     */
    class MyRunnable implements Runnable{

        @Override
        public void run() {
            while (true){
                // 鎖住整個類
                synchronized (MyRunnable.class){
                    if(count > 100){
                        break;
                    }
                    System.out.println(Thread.currentThread().getName() + ":count" + (++ count));
                    // 測試時線程容易切換
                    Thread.yield();
                }
            }
        }
    }
}

使用AtomicInteger加線程池

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

public class ThreadTest1 {

    static CountDownLatch cdl = new CountDownLatch(100);
    static AtomicInteger ai = new AtomicInteger(0);

    public static void main(String[] args) throws InterruptedException {
        ExecutorService exec = Executors.newFixedThreadPool(10);

        for (int i = 0; i < 100; i++) {
            exec.execute(() -> {
                    System.out.println(Thread.currentThread().getName() + ":" + ai.getAndIncrement());
                    cdl.countDown();
            });
        }

        cdl.await();
        System.out.println(ai.get());
        exec.shutdown();
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章