0

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.

Please geeks assit me.

Arsene
  • 1,037
  • 4
  • 20
  • 47
  • You need to create threads to run tasks asynchronously. There are various ways to do that depending on context (GUI or not, number of tasks, recurrence...). – assylias Feb 22 '13 at 15:06
  • 4
    You need to do some research. I recommend starting here: http://www.vogella.com/articles/JavaConcurrency/article.html – Gray Feb 22 '13 at 15:10
  • If you haven’t done much concurrent programming before, you might want to read that Vogella tutorial slowly and from top to bottom, which is strongly recommended since you must make your code thread-safe first. If you feel adventurous, you can also dive right into it: http://www.vogella.com/articles/JavaConcurrency/article.html#threadpools and scroll upwards later. Think in tasks, not in threads. – Ralf H Feb 22 '13 at 15:19

3 Answers3

0

As @Gray suggested, doing research is probably the best thing to do. Take a look at The Fork/Join Framework, or at some other Executor Services. Without knowing more about what you are doing it is hard to give better suggestions about what would be appropriate.

This also gives some examples of where to start.

Community
  • 1
  • 1
John Kane
  • 4,383
  • 1
  • 24
  • 42
0

You can use the Executors (since 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

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();
  }
}
OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213