首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java ThreadPool报表

Java ThreadPool报表
EN

Stack Overflow用户
提问于 2014-03-22 05:57:35
回答 2查看 98关注 0票数 0

我设置了一个工作线程池来执行一些工作,我希望将这些工作记录在一个中心位置。

更准确地说,我将Thread类扩展为worker类,用于检查并发队列的状态。如果它是空的,那么它会等待。当元素被另一个线程添加时,notify()唤醒工作线程。一旦他们完成了任务,他们就等待队列中的下一个元素。

让每个线程在每个任务结束时报告其状态的最佳实践是什么?

代码语言:javascript
复制
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 
             }
}
EN

回答 2

Stack Overflow用户

发布于 2014-04-01 03:34:00

如前所述,最好的方法是使用BlockingQueue。以下是示例代码:

代码语言:javascript
复制
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

票数 0
EN

Stack Overflow用户

发布于 2014-04-01 03:38:31

试着这样做

代码语言:javascript
复制
ExecutorService exec = Executors.newFixedThreadPool(10);
    Runnable runn = new Runnable() 
    {
        @Override
        public void run() 
        {
            System.out.println("");
        }
    };
    exec.execute(runn);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22570249

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档