【发布时间】: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