等待线程完成后再继续

时间:2011-09-22 17:15:27

标签: java android multithreading

当用户启动我的Android应用程序时,我会启动2个线程在后台进行一些处理。 thread_1在客户端上进行一些计算,而thread_2从服务器获取一些数据。一切正常。没有线程修改UI。我有两个跟进问题。

new Thread(new Runnable(){
    @Override
    public void run(){
        MyClass.someStaticVariable = doSomeCalculations();
    }
}).start();
  1. 从线程的run()方法中检索数据的最佳做法是什么?我目前有一个静态变量,我将相关计算数据/获取数据分配给它。或者是否建议使用Handler类从线程中获取数据?我想如果他们希望更新UI,只会使用处理程序。

    while(true)
    {
        if (!thread1.isAlive() && !thread2.isAlive())  
        {
            startActivity(intent)
        }
    }
    
  2. 我需要等到两个线程都完成才能通过Intent从两个线程传递数据。我怎样才能做到这一点?我可以使用上面显示的代码来完成它,但这似乎不对。

4 个答案:

答案 0 :(得分:12)

你可以使用未来。在数据可用之前,它将阻止get:http://developer.android.com/reference/java/util/concurrent/Future.html

另一种方法是将CountDownLatch传递给线程,并在退出run方法时调用countDown():http://developer.android.com/reference/java/util/concurrent/CountDownLatch.html

final CountDownLatch latch = new CountDownLatch(2);
new Thread(new Runnable(){
  @Override
  public void run(){
    // Do something
    latch.countDown()
  }
}).start();
new Thread(new Runnable(){
  @Override
  public void run(){
    // Do something
    latch.countDown()
  }
}).start();

latch.await()
startActivity(intent)

答案 1 :(得分:1)

  1. 您可以使用共享对象(通过指向它的静态字段或任何其他方式),但您必须知道两件事。首先,两个线程访问的对象存在同步问题。使用不可变对象来缓存它。第二,如何通知另一个线程新的共享数据可用 - 这取决于你的其他线程在做什么。

  2. 设置两个线程完成时检查或设置的公共标志。这样线程可以检查其他标志是否在它之前完成。

答案 2 :(得分:1)

使用callable / Future / ExecutorService将是在reqular java应用程序中执行此操作的最简洁方法(对于android也应该是相同的)

ExecutorService executor = Executors.newFixedThreadPool(2);
Future<Integer> firstThreadResult = executor.submit(new Callable<Integer>() {
   Integer call() {
   }
});

Future<Integer> secondThreadResult = executor.submit(new Callable<Integer>() {
   Integer call() {
   }
});

executor.shutdown();
executor.awaitTermination(Integer.MAX_VALUE,TimeUnit.SECONDS); // or specify smaller timeout
// after this you can extract the two results
firstThreadResult.get();
secondThreadResult.get();

更详细example

答案 3 :(得分:0)

对于查询1:

  

从线程的run()方法检索数据的最佳做法是什么?

除了[Google::Apis::ServerError] An error occurred on the server and the request can be retried [Google::Apis::ClientError] The request is invalid and should not be retried without modification [Google::Apis::AuthorizationError] Authorization is required 之外,您还可以使用线程Future方法中的回调机制。在此run()方法中,将值传递给调用者对象或在对象中设置相关值。

Implementing callbacks in Java with Runnable

对于查询2:

  

我需要等到两个线程都完成才能通过Intent

从两个线程传递数据

除了基本的run() API,您还可以通过多种方式实现它。

1。ExecutorService join() API

  

执行给定的任务,在完成所有任务后返回持有其状态和结果的Futures列表。

2。CountDownLatch

  

允许一个或多个线程等待直到在其他线程中执行的一组操作完成的同步辅助。

3. ForkJoinPool中的ExecutorsinvokeAll()

请参阅此相关的SE问题:

wait until all threads finish their work in java