Java背景线程

我想知道如何最好地实现后台来执行某些任务。 根据任务中的某些条件,它将结束并返回调用者的状态。 此外,当后台线程正在运行时,它不应该阻止调用程序线程等待其完成。 我尝试过FutureTask但它同步完成所有事情。

请极客帮我。

您可以使用Executors(自java 1.5起) http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/Executors.html

Executor executor= Executors.newSingleThreadExecutor(); Future future = executor.sumbit(new MyCallable()); // new thread running... // ....... // synchronize/join..... executor.shutdown(); executor.awaitTermination(30, TimeUnit.MINUTES); // also you can do... (Get --> Waits if necessary for the computation to complete, and then retrieves its result.) ReturnType myreturn = future.get(); 

正如@Gray建议的那样,做研究可能是最好的事情。 看看The Fork / Join Framework ,或者其他一些Executor Services 。 如果不了解您正在做的事情,很难就什么是合适的提供更好的建议。

这也给出了从哪里开始的一些例子。

这是一个非常简单的双线程示例。 你应该可以修改它来做你需要的几乎任何事情。 我会用队列来返回你的结果。 查看消费者如何poll队列,您可以在主线程中执行此操作以等待线程的结果。

 public class TwoThreads { public static void main(String args[]) throws InterruptedException { System.out.println("TwoThreads:Test"); new Test().test(); } // The end of the list. private static final Integer End = -1; static class Producer implements Runnable { final Queue queue; private int i = 0; public Producer(Queue queue) { this.queue = queue; } @Override public void run() { try { for (int i = 0; i < 1000; i++) { queue.add(i++); Thread.sleep(1); } // Finish the queue. queue.add(End); } catch (InterruptedException ex) { // Just exit. } } } static class Consumer implements Runnable { final Queue queue; private int i = 0; public Consumer(Queue queue) { this.queue = queue; } @Override public void run() { boolean ended = false; while (!ended) { Integer i = queue.poll(); if (i != null) { ended = i == End; System.out.println(i); } } } } public void test() throws InterruptedException { Queue queue = new LinkedBlockingQueue(); Thread pt = new Thread(new Producer(queue)); Thread ct = new Thread(new Consumer(queue)); // Start it all going. pt.start(); ct.start(); // Wait for it to finish. pt.join(); ct.join(); } }