使用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++;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值