gpt4 book ai didi

java - 如何更改线程执行顺序,使最后创建的线程先运行?

转载 作者:行者123 更新时间:2023-12-01 11:47:44 26 4
gpt4 key购买 nike

我们动态添加线程。首先数量为 1,然后开始运行,一旦创建第 2_nd 线程,第一个线程就应该阻塞,第 2_nd 线程应该执行,当第 2_nd 线程完成任务时,第 1_st 线程继续执行。this应该适用于动态 N 个线程。我需要顺序工作线程和单线程执行。onItemClick 每次创建线程并需要最后创建的线程执行其他等待时。这是 onItemClick 中的代码而在我的代码中,它按顺序工作。一个完成然后启动另一个

Thread testThread = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(5000);
for (int i = 0; i < 15; i++) {

Log.i("log", "name = " + i + Thread.currentThread().getName());
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "ThreadName=" + magazineId);



try {
Thread currentThread = Thread.currentThread();
if(Looper.getMainLooper().getThread() != currentThread) {
// Current Thread is Main Thread.
currentThread.join(100);
}

} catch (InterruptedException e) {
e.printStackTrace();
}
testThread.start();

最佳答案

查看 Naman Gala 发布的链接,我认为您正在寻找的是 join()。

来自帖子:

join() If any executing thread t1 calls join() on t2 i.e; t2.join() immediately t1 will enter into waiting state until t2 completes its execution.

关于java - 如何更改线程执行顺序,使最后创建的线程先运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29024873/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com