【问题标题】:I'm trying to make a program with 2 racers and it keeps giving me an IllegalThreadStateException我正在尝试用 2 个赛车手制作一个程序,但它一直给我一个 IllegalThreadStateException
【发布时间】:2019-04-13 21:58:37
【问题描述】:

我的程序中有 2 个线程和一个主类,每当我尝试运行它时,一个线程都会给我一个 IllegalThreadStateException,我不知道为什么。程序需要做一个龟兔赛跑,乌龟可以跑10米,直到300米才停止,兔子可以跑100米,但需要90%的时间休息。以下是我的代码,如果有人可以帮助我,我将不胜感激。此外,当我让它运行时,Hare 线程只是输出 Hare: 0 一百万次,所以我也不确定为什么会这样。

主类:

package runnerthread;

public class RunnerThread extends Thread{

    public static void main(String[] args) {
       System.out.println("Get set...Go!");
        int hPosition = Hare.position;
        int tPosition = Tortoise.position;
        Thread hare = new Thread(new Hare());
        Thread tortoise = new Thread(new Tortoise());
        try{
       while(hPosition<300 && tPosition<300){
           tortoise.start();
           hare.start();
           Thread.sleep(300);
       }
        }catch(InterruptedException e){}
}
}

龟线:

public class Tortoise extends Thread {
    static int position;
    static int speed = 10;
    @Override
    public void run(){
            position = speed + 10;
        System.out.println("Tortoise: "+position);
    }
}

野兔线:

import java.util.Random;


public class Hare extends Thread{
     static int position;
    int speed = 100;
    int restingPercent = 90;
    Random random = new Random();
        int randomNum = random.nextInt((100-1)+1) + 1;
    @Override
    public void run(){
    while(position<300){
    if (randomNum<=restingPercent){
        System.out.println("Hare: "+position);
    }else {
        position+=100;
        System.out.println("Hare: "+position);
    }
}
}
}

【问题讨论】:

    标签: java multithreading netbeans illegalstateexception


    【解决方案1】:

    您不能在一个线程上多次调用 start。线程对象不能被重用。您可以为此目的使用 Runnable。有关更多信息,请查看此答案:https://stackoverflow.com/a/2324114/10632970

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-22
      • 1970-01-01
      • 2017-08-01
      • 2019-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多