使用Java多线程设计一个计数器

题目:开启1000个线程,每个线程对计数器进行10000次累加,最终输出结果应该是10000000

public class Test {

    public static void main(String[]args){

        //
进行10次测试
        for (int i = 0; i < 10; i++){
            test();
        }
    }

    public static void test(){
        //
计数器
        Counter counter = new Counter();
        //
线程数量(1000
        int threadCount = 10000;

        //
用来让主线程等待threadCount个子线程执行完毕
        CountDownLatch countDownLatch = new CountDownLatch(threadCount);

        //
启动子线程
        for (int i = 0; i < threadCount; i++){
            Thread thread = new Thread(new MyThread1(counter,countDownLatch));
            thread.start();
        }
        try {
            //
主线程等待所有子线程执行完成,再向下执行
            countDownLatch.await();
        }catch (InterruptedException e){
            e.printStackTrace();
        }

        //
计数器的值
        System.out.println(counter.getCount());
    }


}
 class MyThread1 implements Runnable{

    private Counter counter;
    private CountDownLatch countDownLatch;
    public MyThread1(Counter counter, CountDownLatch countDownLatch){
        this.counter = counter;
        this.countDownLatch = countDownLatch;
    }
    @Override
    public void run() {
        //
每个线程向Counter中进行10000次累加
        for (int i = 0; i < 1000; i++){
            counter.addCount();
        }

        //
完成一个子线程
        countDownLatch.countDown();
    }
}


class Counter{
    private int count = 0;
    public int getCount(){
        return count;
    }

//使用关键字synchronized实现线程安全。    

public synchronized void addCount(){
        count++;
    }
}

 


版权声明:本文为qq_35265007原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。