在多线程中:如何确定首先停止哪个线程 [英] In multithreading: How to determine which thread stops first

查看:190
本文介绍了在多线程中:如何确定首先停止哪个线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编写一个名为RaceHorse的类,它扩展了Thread。每个RaceHorse都有一个名称和run()方法,显示名称5000次。编写一个实例化2个RaceHorse对象的Java应用程序。完成的最后一个RaceHorse是失败者。

这就是问题所在。
我已经写了两个类的代码两个运行线程
以下是代码:

This is the question. I have written the code for the two classes two run the thread Here are the codes:

RaceHorse

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

First off: your RaceHorse objects are themselves threads. You should be able to say obj.start(); and it'd work just as well. So remove t and t2 entirely.

接下来,你需要一些方法来通知主线程有关获胜者。

Next, you'll need some way to notify the main thread about the winner.

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

这篇关于在多线程中:如何确定首先停止哪个线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆