public class ThreadService extends Thread{
public ThreadService(){ } public void run(){
int i =0 ;
while(true){
try{
sleep(100);}
catch(Exception e){
System.out.println("线程执行异常");
}
System.out.println("执行到"+i);
i = i+1;
}
} public static void main (String[] arg){
ThreadService threadService = new ThreadService();
threadService.start();
threadService.stop();
threadService.start();
}
}
}在上面代码中执行线程的开关的时候,会产生如下异常:Exception in thread "main" java.lang.IllegalThreadStateException
at java.lang.Thread.start(Thread.java:638)
at com.ThreadService.main(ThreadService.java:25)我查了下,好像是线程运行状态不对。
public ThreadService(){ } public void run(){
int i =0 ;
while(true){
try{
sleep(100);}
catch(Exception e){
System.out.println("线程执行异常");
}
System.out.println("执行到"+i);
i = i+1;
}
} public static void main (String[] arg){
ThreadService threadService = new ThreadService();
threadService.start();
threadService.stop();
threadService.start();
}
}
}在上面代码中执行线程的开关的时候,会产生如下异常:Exception in thread "main" java.lang.IllegalThreadStateException
at java.lang.Thread.start(Thread.java:638)
at com.ThreadService.main(ThreadService.java:25)我查了下,好像是线程运行状态不对。
/* Java thread status for tools,
* initialized to indicate thread 'not yet started'
*/private int threadStatus = 0;
线程没启动状态为0, 启动之后状态就不为0了, start方法中会判断这个状态的