开发者

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

开发者 https://www.devze.com 2023-02-17 16:12 出处:网络
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 orderYou can start the second thre

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

精彩评论

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