我设置了一个工作线程池来执行一些工作,我希望将这些工作记录在一个中心位置。
更准确地说,我将Thread类扩展为worker类,用于检查并发队列的状态。如果它是空的,那么它会等待。当元素被另一个线程添加时,notify()唤醒工作线程。一旦他们完成了任务,他们就等待队列中的下一个元素。
让每个线程在每个任务结束时报告其状态的最佳实践是什么?
public class PoolWorker extends Thread {
public ConcurrentLinkedQueue<Device> q;
public PoolWorker(ConcurrentLinkedQueue<Device> q, String type){
this.q = q;
this.type = type;
}
@Override
public void run(){
while (true)
{
Device d = null;
try{
synchronized(q){
while(q.isEmpty())
{
q.wait(); // wait for a notify()
}
d = q.remove();
}
// do some work
// report status of work completed
}
}发布于 2014-04-01 03:34:00
如前所述,最好的方法是使用BlockingQueue。以下是示例代码:
public class PoolWorker extends Thread {
public ArrayBlockingQueue<String> q;
public String type;
public PoolWorker(ArrayBlockingQueue<String> q, String type) {
this.q = q;
this.type = type;
}
@Override
public void run() {
while(true){
String work = null;
try {
System.out.println("PoolWorker.run:waiting .............");
work = q.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("PoolWorker.run..work: " + work);
}
}
public static void main(String[] args) throws InterruptedException {
ArrayBlockingQueue<String> pool = new ArrayBlockingQueue<String>(100);
PoolWorker worker = new PoolWorker(pool, "Something");
worker.start();
addWork(pool, "work1");
addWork(pool, "work2");
addWork(pool, "work3");
addWork(pool, "work4");
addWork(pool, "work5");
//Just give enough time to run
Thread.sleep(5000);
}
private static void addWork(ArrayBlockingQueue<String> pool, String work) throws InterruptedException {
System.out.println("PoolWorker.addWork: " + work);
pool.put(work);
}
}在Java文档中也有很好的示例代码:http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/BlockingQueue.html
发布于 2014-04-01 03:38:31
试着这样做
ExecutorService exec = Executors.newFixedThreadPool(10);
Runnable runn = new Runnable()
{
@Override
public void run()
{
System.out.println("");
}
};
exec.execute(runn);https://stackoverflow.com/questions/22570249
复制相似问题