作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我创建了这两个线程(在其他类(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/
我是一名优秀的程序员,十分优秀!