Java后台线程 [英] Java Background thread

查看:53
本文介绍了Java后台线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to know how best to implement a background to perform some tasks. Based upon some conditions within the tasks it will end and return a state the caller. Also whilst that background thread is running it should not prevent the caller thread to wait for its completion. I have tried FutureTask but it does everything synchronously.

请极客们帮助我.

推荐答案

这是一个非常简单的双线程示例.您应该能够对其进行修改以执行几乎任何您需要的操作.我会使用队列来返回你的结果.查看消费者如何轮询队列,您可以在主线程中执行此操作以等待线程的结果.

Here's a very simple two-threads example. You should be able to modify it to do almost anything you need. I would use the queue to return your result. See how the consumer polls the queue, you can do that in your main thread to await results from your thread.

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

这篇关于Java后台线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆