2013-02-22 128 views
0

我想知道如何最好地實現背景來執行一些任務。根據任務中的一些條件,它將結束並返回一個狀態的調用者。此外,當後臺線程正在運行時,它不應阻止調用者線程等待其完成。我已經嘗試過FutureTask,但它同步完成所有事情。Java後臺線程

請怪人幫我。

+0

您需要創建線程以異步運行任務。有多種方式可以根據上下文(GUI或不,任務數量,重複次數...)進行。 – assylias 2013-02-22 15:06:38

+4

你需要做一些研究。我建議從這裏開始:http://www.vogella.com/articles/JavaConcurrency/article.html – Gray 2013-02-22 15:10:00

+0

如果你之前沒有做太多的併發編程,你可能想慢慢地從上到下閱讀Vogella教程,它強烈建議,因爲您必須首先使您的代碼線程安全。如果你覺得冒險,你也可以直接進入它:http://www.vogella.com/articles/JavaConcurrency/article.html#threadpools和稍後向上滾動。在任務中思考,而不是在線程中。 – 2013-02-22 15:19:01

回答

0

正如@格雷所建議的,做研究可能是最好的選擇。看看The Fork/Join Frameworksome other Executor Services。如果不瞭解更多關於你在做什麼的事情,很難就什麼是合適的提供更好的建議。

This也給出了一些從哪裏開始的例子。

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