gpt4 book ai didi

java - 如何知道哪个线程先完成

转载 作者:行者123 更新时间:2023-11-30 05:21:33 37 4
gpt4 key购买 nike

我创建了这两个线程(在其他类(class)中,我给了它们对我的问题不重要的属性)

我想知道如何知道哪个线程先完成

public class Race {

public static void main(String[] args) {

try {
Thread th1 = new Thread(new Dog("Bubu",2));
Thread th2 = new Thread(new Rabbit("Lepri",3));
th1.start();
th2.start();

} catch (GaraException ex) {
Logger.getLogger(Gara.class.getName()).log(Level.SEVERE, null, ex);
}
}
}

最佳答案

无需忙循环或为每个要加入的线程启动线程:

        AtomicReference<Thread> first = new AtomicReference<>();

Dog bubu = new Dog("Bubu",2);
Thread th1 = new Thread(() -> {
bubu.run();
first.compareAndSet(null, Thread.currentThread());
}, "Bubu");

Rabbit lepri = new Rabbit("Lepri",3);
Thread th2 = new Thread(() -> {
lepri.run();
first.compareAndSet(null, Thread.currentThread());
}, "Lepri");

th1.start();
th2.start();
th1.join();
th2.join();

System.err.println("First: "+first);

关于java - 如何知道哪个线程先完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59494264/

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