日期:2014-05-18  浏览次数:20937 次

刚接触多线程,有点晕,请教一下
import   java.util.ArrayList;
class   R   implements   Runnable   {
private   int   i;
ArrayList   a   =   new   ArrayList();
public   int   getI()   {
return   i;
}
public   void   setI(int   i)   {
this.i   =   i;
}
public   void   run()   {
// synchronized   (a)   {
a.add(i);
//}
}
public   ArrayList   getA()   {
return   a;
}
public   void   setA(ArrayList   a)   {
this.a   =   a;
}
}

import   java.util.ArrayList;

public   class   Test   {
public   static   void   main(String[]   args)   throws   Exception   {
long   a1   =   System.currentTimeMillis();
R   r=   new   R();
Thread   t=new   Thread(r);
//r.setI(9);
for(int   i=0;i <100;i++){
r.setI(i);
System.out.println( "t== "+i);
t.start();
t.sleep(1000);
}
ArrayList   l   =   r.getA();
for(int   i=0;i <l.size();i++){
System.out.println(l.get(i));
}
long   b1   =   System.currentTimeMillis();
System.out.println(b1-a1);
}
}

请问为什么产生Exception   in   thread   "main "   java.lang.IllegalThreadStateException
at   java.lang.Thread.start(Thread.java:571)
at   Test.main(Test.java:15)
我该怎么修改呢?谢谢

------解决方案--------------------
一个线程怎么能启动很多次呢

你在循环里面调用 t.start(); 肯定会报错


------解决方案--------------------


import java.util.ArrayList;

class R implements Runnable {
private int i;

ArrayList a = new ArrayList();

public int getI() {
return i;
}

public void setI(int i) {
this.i = i;
}

public void run() {
for (int ii = 0; ii < 100; ii++) {

a.add(i);
this.setI(ii);
System.out.println( "t== " + i);
try {
Thread.sleep(100);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}

public ArrayList getA() {
return a;
}

public void setA(ArrayList a) {
this.a = a;
}
}

public class Test2 {
public static void main(String[] args) throws Exception {
long a1 = System.currentTimeMillis();
R r = new R();
Thread t = new Thread(r);
t.start();
ArrayList l = r.getA();

}
}

------解决方案--------------------
不太明白你
的意思

------解决方案--------------------
同意楼上兄弟
同一个线程不能启动多次,不过你可以在MAIN里启动多个线程
看了你发出的代码,给你做了如下修改,如果没有理解错误的话应该是能实现你原有功能的
package com.philwong.therd;

import java.util.ArrayList;

public class R implements Runnable {

private int i;
ArrayList a = new ArrayList();
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
public void run() {
// synchronized (a) {
a.add(i);
//}
}
public ArrayList getA() {