多线程计数器

package com.wk.thread.count;

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

/**
 * 测试AtomicInteger与普通int值在多线程下的递增操作
 */
public class TestAtomicInteger {
	final static int threads = 123;//线程数
	final int singleThread = 456;//每次线程执行的循环数
	static AtomicInteger atomic = new AtomicInteger(0);//初始化计数器
	public static void main(String[] args) throws InterruptedException {
		CountDownLatch countDownLatch = new CountDownLatch(threads);//初始化倒序计数器
		ExecutorService executors = Executors.newFixedThreadPool(threads);//固定线程池
		for(int i= 0;i<threads;i++){//调用自定义线程去执行
			executors.execute(new TestAtomicInteger().new mythread(countDownLatch));
		}
		countDownLatch.await();//等待倒序线程池都执行完毕
		System.out.println(atomic.getAndIncrement());//输出计数器
	}
	class mythread extends Thread{//implements Runnable{
		private CountDownLatch countDownLatch;//构造方法,传入倒序计数器
		public mythread(CountDownLatch countDownLatch){
			this.countDownLatch = countDownLatch;
		}
		@Override
		public void run() {
			for(int i=0;i<singleThread;i++){//每次循环改变计数器
				atomic.incrementAndGet();
			}
			countDownLatch.countDown();//执行完毕后,结束倒序计时器
		}
		
	}
	
}


参考地址:

http://blog.csdn.net/longerandlonger/article/details/8276869(一个使用线程计数器的例子

http://www.jb51.net/article/55373.htm(Java中对AtomicInteger和int值在多线程下递增操作的测试

http://blog.csdn.net/is_zhoufeng/article/details/8151092(java线程池 与 同步计数器CountDownLatch的使用

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值