有关线程的问题,大神进来看一下!
看下以下两个代码,为什么我一个代码会出现异常java.lang.IllegalThreadStateException. 而第二种方法就产生了异常了呢? 同样是通过Thread中的 public Thread(Runnable target)构造方法创建了对象. 疑惑啊....------------------------------------------------------------------------------------------------------------------------------------------------ -----------------------------------------------------------------------------------------------------------------------------------------------
第一种:
class MyThread1 implements Runnable{
int tickets=5;
private String name;
public MyThread1(String name){
this.name=name;
}
public void run(){
for(int i=0;i<5;i++){
System.out.println("余票还有:"+(--tickets));
}
}
}
public class ThreadDemo2 {
public static void main(String args[]){
MyThread1 mt1= new MyThread1("线程1");
Thread th1=new Thread(mt1);
th1.start();
th1.start();
}
}
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
第二种:class MyThread1 implements Runnable{
int tickets=5;
private String name;
public MyThread1(String name){
this.name=name;
}
public void run(){
for(int i=0;i<5;i++){
System.out.println("余票还有:"+(--tickets));
}
}
}
public class ThreadDemo2 {
public static void main(String args[]){
MyThread1 mt1= new MyThread1("线程1");
new Thread(mt1).start();
new Thread(mt1).start();
}
}