Java背景线程

时间:2013-02-22 15:01:11

标签: java multithreading

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

请极客帮我。

3 个答案:

答案 0 :(得分:0)

正如@Gray建议的那样,做研究可能是最好的事情。请查看The Fork/Join Frameworksome other Executor Services。如果不了解您正在做的事情,很难就什么是合适的事情给出更好的建议。

This还提供了一些从哪里开始的例子。

答案 1 :(得分:0)

你可以使用Executors(因为java 1.5) http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/Executors.html

Executor executor= Executors.newSingleThreadExecutor();
Future<ReturnType> future = executor.sumbit(new MyCallable<ReturnType>());

// 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();

答案 2 :(得分:0)

这是一个非常简单的双线程示例。你应该可以修改它来做几乎你需要的任何事情。我会用队列来返回你的结果。查看消费者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<Integer> queue;
    private int i = 0;

    public Producer(Queue<Integer> 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<Integer> queue;
    private int i = 0;

    public Consumer(Queue<Integer> 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();
  }
}