我想知道如何最好地实现背景来执行一些任务。根据任务中的一些条件,它将结束并返回一个状态的调用者。此外,当后台线程正在运行时,它不应阻止调用者线程等待其完成。我已经尝试过FutureTask,但它同步完成所有事情。Java后台线程
请怪人帮我。
我想知道如何最好地实现背景来执行一些任务。根据任务中的一些条件,它将结束并返回一个状态的调用者。此外,当后台线程正在运行时,它不应阻止调用者线程等待其完成。我已经尝试过FutureTask,但它同步完成所有事情。Java后台线程
请怪人帮我。
正如@格雷所建议的,做研究可能是最好的选择。看看The Fork/Join Framework或some other Executor Services。如果不了解更多关于你在做什么的事情,很难就什么是合适的提供更好的建议。
This也给出了一些从哪里开始的例子。
可以使用执行人(由于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();
这里是一个非常简单的两线的例子。你应该可以修改它来完成你需要的任何事情。我会使用队列来返回你的结果。看看消费者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();
}
}
您需要创建线程以异步运行任务。有多种方式可以根据上下文(GUI或不,任务数量,重复次数...)进行。 – assylias 2013-02-22 15:06:38
你需要做一些研究。我建议从这里开始:http://www.vogella.com/articles/JavaConcurrency/article.html – Gray 2013-02-22 15:10:00
如果你之前没有做太多的并发编程,你可能想慢慢地从上到下阅读Vogella教程,它强烈建议,因为您必须首先使您的代码线程安全。如果你觉得冒险,你也可以直接进入它:http://www.vogella.com/articles/JavaConcurrency/article.html#threadpools和稍后向上滚动。在任务中思考,而不是在线程中。 – 2013-02-22 15:19:01