编写一个扩展 Thread 的名为 RaceHorse 的类。每个 RaceHorse 都有一个名称和显示名称 5000 次的 run() 方法。编写一个实例化 2 个 RaceHorse 对象的 Java 应用程序。最后完成的赛马为输家。
这就是问题。 我已经为两个运行线程的两个类编写了代码 以下是代码:
赛马
class RaceHorse extends Thread
{
public String name;
public RaceHorse(String name)
{
this.name = name;
}
public void run()
{
for(int i = 1 ; i <= 5000; i++)
{
System.out.println(i+" "+name);
}
System.out.println(name+" finished.");
}
}
运行者
class Runner{
public static void main(String args[])
{
RaceHorse obj = new RaceHorse("Lol");
RaceHorse obj2 = new RaceHorse("BOL");
Thread t = new Thread(obj);
Thread t2 = new Thread(obj2);
t.start();
t2.start();
}
}
现在我的问题是我无法找到哪一个线程先完成,哪一秒完成,即哪匹马赢了,哪匹马输了。!
最佳答案
首先:您的RaceHorse
对象本身就是线程。您应该可以说 obj.start();
并且它也能正常工作。因此,完全删除 t
和 t2
。
接下来,您需要通过某种方式通知主线程获胜者。
public void run()
{
... your loop stuff ...
// this is how we're going to do the notification.
Runner.done();
}
public class Runner
{
private static RaceHorse winner = null;
synchronized static void done()
{
// Threads calling this are going to be RaceHorse objects.
// Now, if there isn't already a winner, this RaceHorse is the winner.
if (winner == null) winner = (RaceHorse) Thread.currentThread();
}
public static void main(String[] args)
{
... create the horses ...
// start the horses running
obj.start();
obj2.start();
// wait for them to finish
obj.join();
obj2.join();
System.out.println(winner.name + " wins!");
}
}
关于java - 在多线程中 : How to determine which thread stops first,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3381619/