LinkedBlockingQueue是线程安全的,不信看这儿

本文介绍了一个使用Java实现的多线程并发队列测试案例。测试中创建了一个包含10个线程的池,每个线程从共享的BlockingQueue中取元素,并记录所取出的元素数量。测试结束后,统计所有线程取出的元素总数。
package test;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import org.junit.Test;

public class QueueTest {

	public static final BlockingQueue<Integer> queue = new LinkedBlockingQueue<Integer>();
	
	private int thread_num = 10;
	private List<QueueThread> runList = null;
	
	@Test
	public void testQueue(){
		runList = new ArrayList<QueueThread>(thread_num);
		System.out.println("初始化---");
		for(int i = 0 ; i < thread_num ; i++){
			QueueThread qt = new QueueThread(i);
			Thread thread =  new Thread(qt);
			thread.start();
			runList.add(qt);
		}
		System.out.println("启动线程完成---");
		
		for(int j = 0 ; j< 100; j++){
			queue.add(j);
		}
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		int all = 0;
		for(QueueThread qt : runList){
			System.out.println(qt);
			all += qt.num();
		}
		System.out.println("all:" + all);
	}
}

class QueueThread implements Runnable{

	private int num;
	
	List<Integer> strList = null;
	
	public QueueThread(int num) {
		super();
		this.num = num;
		strList = new ArrayList<Integer>();
	}

	public void run() {
		try {
			while(true){
				Integer i = QueueTest.queue.take();
				strList.add(i);
				System.out.println("线程" + num + "take:" + i);
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
	}
	
	@Override
	public String toString(){
		return "线程" + num + "take num:" + strList.size();
	}
	
	public int num(){
		return this.strList.size();
	}
	
}

转载于:https://www.cnblogs.com/near/archive/2010/11/18/1880944.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值