开发者

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

i have more than one handler (thread) execute , and so开发者_Python百科me thread depends on the result of other one .. so i want to make threads execute in a defined order


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,

Somewhere common share the latch CountdownLatch latch = new CountdownLatch(1);

Thread 1,

 doSomething();
 countdownLatch.countdown();

Thread 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. LinkedBlockingQueue, CyclicBarrier, Exchanger may be useful. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜