先实现Thread代码
public class TestThread {
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
myThread.start();
System.out.println(myThread.getName() + "---" + i + "---");
}
}
static Thread myThread = new Thread(new Runnable() {
int count = 0;
boolean runable = true;
public void run() {
while (runable) {
count++;
try {
Thread.sleep(100);
} catch (Exception e) {
}
if (count > 100) {
runable = false;
}
}
}
});
}
运行结果:
Thread-0---0---
Exception in thread "main" java.lang.IllegalThreadStateException
at java.lang.Thread.start(Unknown Source)
at TestThread.main(TestThread.java:6)
当第二次调用Thread.start()启动同一个线程时,报错。
采用Runnable实现,解决问题
public class TestRunnable {
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
Thread t = new Thread(myRunnable);
t.start();
System.out.println( t.getName() + "---" + i + "---");
}
}
static Runnable myRunnable = new Runnable() {
int count = 0;
boolean runable = true;
@Override
public void run() {
while (runable) {
count++;
try {
Thread.sleep(100);
} catch (Exception e) {
}
if (count > 100) {
runable = false;
}
}
}
};
}
运行结果正常。可以启动多个线程
2016/8/16修改编辑
Thread报错的原因,并不是说,重新启动Thread导致的,而是因为共用一个Thread导致的,因为,如果是实现Runnable的类,每次启动线程都需要new Thread(Runnable).start(),这就使得线程没有被共用。所以,另外一种解决办法是如下:
public class TestThread {
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
// TestThread t = new TestThread();
new TThread().start();
// myThread.start();
// System.out.println(myThread.getName() + "---" + i + "---");
}
Thread.currentThread();
}
}
class TThread extends Thread{
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
System.out.println("111");
}
}
只要每次都new 一个新的线程对象,就不会报错。