简体   繁体   English

如何允许两个线程在android中以预定义的顺序执行?

[英]How th allow two threads execute in a predefined order in android?

我有多个处理程序(线程)执行,一些线程依赖于其他的结果..所以我想让线程以定义的顺序执行

You can start the second thread from the first thread. 您可以从第一个线程启动第二个线程。

final Thread th2 = new Thread(new Runnable(){
    public void run(){
        doSomething2;
    }
}
Thread th1 = new Thread(new Runnable(){
    public void run(){
        doSomething;
        th2.start();
    }
});
th1.start();
th2.join();

But you most probably don't need the second thread at all: 但你很可能根本不需要第二个线程:

Thread th1 = new Thread(new Runnable(){
    public void run(){
        doSomething;
        doSomething2;
    }
});
th1.start();
th1.join();

If you have to wait in one thread for another thread to complete, there are several options. 如果您必须在一个线程中等待另一个线程完成,则有几个选项。

One is to use a CountdownLatch, 一个是使用CountdownLatch,

Somewhere common share the latch CountdownLatch latch = new CountdownLatch(1); 某处常见的共享锁存器CountdownLatch latch = new CountdownLatch(1);

Thread 1, 线程1,

 doSomething();
 countdownLatch.countdown();

Thread 2, 线程2,

 countdownLatch.await();
 doSomethingElse();

Countdown latches can only be used once though. 倒计时锁存器只能使用一次。

There are a bunch of other classes in java.util.concurrent that may solve your problem. java.util.concurrent中有许多其他类可以解决您的问题。 LinkedBlockingQueue, CyclicBarrier, Exchanger may be useful. LinkedBlockingQueue,CyclicBarrier,Exchanger可能很有用。 Its hard to say more without knowing more details. 如果不了解更多细节,很难说更多。

And as the comment and other answer pointed out, if you can, just avoid multiple threads altogether. 正如评论和其他答案所指出的那样,如果可以,只需完全避免多个线程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM