0

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

请极客帮助我。

4

3 回答 3

0

正如@Gray 建议的那样,做研究可能是最好的选择。查看Fork/Join Framework其他一些 Executor Services。如果不了解更多关于你在做什么的信息,就很难就什么是合适的提供更好的建议。

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

于 2013-02-22T15:14:52.773 回答
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();
  }
}
于 2013-02-22T15:21:34.767 回答
0

您可以使用执行器(自 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();
于 2013-02-22T15:19:51.503 回答