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