本文介绍了Java线程-第一个线程完成时关闭其他线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉,我的问题是我有3个线程.

Folks so my problem is that I have 3 Threads.

1Thread(Bot1)

1Thread(Bot1)

public class Bot1 implements Runnable {
  String name;

  public Bot1(String s) throws Exception{
    ChatterBotFactory factory = new ChatterBotFactory();
    ChatterBot bot1 = factory.create(ChatterBotType.CLEVERBOT);
    ChatterBotSession bot1session = bot1.createSession();
    name=s;
    name=bot1session.think(s);
  }

  public void run(){
    System.out.println("b1: "+name);
  }
}

其他都一样.只有名称为Bot2Bot3.但是代码几乎相同.我需要同时启动这些机器人.我只需要显示最快的句子.示例:如果Bot1显示"Hello"的速度比Bot2Bot3快,那么我需要关闭Bot2Bot3线程. 但是我怎么看哪一个更快?我需要关闭并重新运行我的哪两个代码?我希望您理解我并能为我提供帮助.谢谢你,我的英语不好.

And the others are same. Only names are Bot2 and Bot3. But the code is almost same.I need to start these bots at the same time. And I need to display only the sentence that is fastest. Example: if Bot1 displayed "Hello" faster than Bot2 and Bot3, then I need to close the Bot2 and Bot3 thread. But how do I see which one was faster? And which two do I need to close and run my code again? I hope You understand me and can help me. Thank you and sorry for my bad English.

推荐答案

我会尝试在每个bot中使用boolean isRunning,在run方法中使用while(isRunning).然后在第四个线程中,检查所有的机器人,看看是否完成了.如果已完成,请将其他机器人的isRunning设置为false,它们应退出.

I would try having a boolean isRunning in each bot and in the run method have a while(isRunning). Then in a fourth thread, check through all of the bots and see if any are done. If one is done, set the isRunning of the others bots to false and they should exit.

这篇关于Java线程-第一个线程完成时关闭其他线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 08:19