如何知道哪个线程先完成

时间:2019-12-26 22:56:49

标签: java

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

我想知道我怎么知道哪个线程先完成

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);
        }
    }
}

2 个答案:

答案 0 :(得分:1)

没有繁忙的循环或启动每个线程加入的线程:

        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);

答案 1 :(得分:0)

Java代码从上到下运行,如果您已经运行了该程序并成功运行,则意味着线程th1将在线程th2之前(从上到下)首先完成。

相关问题