java 多個線程處理一個對象集合

好消息,百度網盤專業搜索網站上線了
打開瞧一瞧:[url]http://bitar.cn[/url]

package com.thread;

import java.sql.SQLException;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class MutiThreadExecutor {

/**
* @param args
* @throws SQLException
*/
public static void main(String[] args) throws SQLException {

MyT t =new MyT();
t.start(10);
for (int i = 0; i < 100; i++) {
t.triggerEvent(""+i);
}
}

}

/**
* 多個線程處理一個對象集合(ConcurrentLinkedQueue),沒有返回結果
* @author Administrator
*
*/
class MyT implements Runnable{
private static Object lock =new Object();

public static ExecutorService exec=null;
boolean running;
ConcurrentLinkedQueue<String> eventQueue = new ConcurrentLinkedQueue<String>();

public void start(int threadCount){
running=true;
exec = Executors.newFixedThreadPool(threadCount);
for (int i = 0; i <threadCount; i++) {
exec.submit(this);
}
}
public void stop(){
running=false;
}
public void triggerEvent(String str) {
synchronized (lock) {
eventQueue.add(str);
lock.notifyAll();
}
}

@Override
public void run() {
while (running) {
synchronized (lock) {
if (eventQueue.isEmpty() && running) {
try {
lock.wait(1000 * 30 );//超時30秒
} catch (InterruptedException ie) {
}
}

}
while (!eventQueue.isEmpty()) {
String event = (String) eventQueue.poll();

if (null != event) {
System.out.println(Thread.currentThread().getId()+":"+event);
}

}

}

}


}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章