等待执行者服务线程

时间:2014-09-22 17:58:04

标签: java multithreading

我有一个使用执行程序服务同时运行任务的类。

代码:

class SomeClass{
private static ExecutorService taskThread = Executors.newFixedThreadPool(1, new ThreadFactory() {
        private int threadCount = 0;

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setDaemon(true);
            return t;
        }
    });

    static {
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                taskThread.shutdown();
            }
        });
    }


doSomeTask()
{
            DocumentUploader callable = new DocumentUploader(randomID,fileLoc);         
            FutureTask<String> task1 = new FutureTask<String>(callable);
            taskThread.execute(task1);
}


someFunctionforWait(){


//what here..???
}

我有另一个类名SomeOtherClass,它将访问task1线程完成的修改/计算。所以我需要等待线程完成,那么我该如何等待task1完成。我打算做的是从类someFunctionforWait()调用SomeOtherClass来检查线程是否已完成,然后开始执行其任务。

我该怎么做。

2 个答案:

答案 0 :(得分:1)

您可以使用Futures,或者如果您想坚持使用ExecutorService,只需等待taskThread.shutdown()和taskThread.awaitTermination();您可以将这些语句放入someFunctionforWait()并在此之后继续执行。以下是基于代码的简化示例:

public class SomeClass {
    private ExecutorService taskThread = Executors.newFixedThreadPool(1);
    private List<Future<String>> futures = new ArrayList<Future<String>>();
    void doSomeTask() {
        FutureTask<String> task1 = new FutureTask<String>(new Callable<String>() {
            public String call() throws Exception {
                System.out.println("thread executing");
                Thread.sleep(1000);
                return Thread.currentThread().toString();
            }
        });
        taskThread.execute(task1);
        futures.add(task1);
    };

    public void someFunctionforWait() throws InterruptedException, ExecutionException{
        taskThread.shutdown();
        taskThread.awaitTermination(5, TimeUnit.SECONDS);
        System.out.println("joined");
    }

    public void someFunctionforWaitAlternative() throws InterruptedException, ExecutionException{
        for(Future<String> future : futures) {
            System.out.println("future val: " + future.get());
        }
        System.out.println("joined");
    }

    public static void main(String[] args) throws Exception {
        SomeClass c = new SomeClass();
        c.doSomeTask();
        c.someFunctionforWait();
        //c.someFunctionforWaitAlternative();
    }
}

答案 1 :(得分:0)

通过taskThread创建Future并在其上调用get()。它会阻止,直到Future完成:

Future<String> f = taskThread.submit(callable); // concurrent operation
String result = f.get();   // blocks until f completes
// use result