您好,欢迎来到华佗小知识。
搜索
您的当前位置:首页LinkedBlockingQueue是线程安全的,不信看这儿

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

来源:华佗小知识
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

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- huatuo0.cn 版权所有 湘ICP备2023017654号-2

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务