如何多次启动线程

来源:百度知道 编辑:UC知道 时间:2024/06/18 12:21:26
我写了一个子线程t1,并在主线程main()里调用它:t1.start().然后t1线程就开始了.但我要反复调用这个子线程.我就把start()写到了一个循环里.但是运行出错,说t1已经started了.大家看怎么改?我是应该只start()一次,以后用别的方法来反复运行它?还是需要写个结束线程的代码,这样就可以重新start了?
很抱歉,那样也不能启动多次

线程如果是 extends Thread 这种,如果你直接的

Thread t = new MyThread();
t.start();

当然只能启动一次。 不过你可以

new Thread(t).start(); 这样就可以启动多次了。
所以建议线程应该 implements Runnable 而不是extends Thread

=====================================================
class MyThread implements Runnable {
。。。。
}

public void main.... {
MyThread t = new MyThread();
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
// 可以启动多次
}

class test{
class mutilthread extends Thread{
public void run(){
//do..
}
}
test(){
for(int i=0;i<10;i++){
new mutilthread().start();
}
}
}

在你这个线程的run方法里面执行循环就可以了

答案补充:
哦 楼上给出答案了,正解!

实验下:
while(true) {
t1 = new Thread1();
t1.start()
} 你每次重新生成这个对象