小弟弄线程时遇到一个麻烦:以下是源程序:public class CountTest implements Runnable { int count= 1, number;
public CountTest(int num)
{
number = num;
System.out.println("Create thread " + number);
} public void run()
{
while(true)
{
System.out.println("thread " + number + ":count " + count);
System.err.println(Thread.currentThread().toString());
//if(++count== 6)
//return; 如果注释掉这两句,怎样结束这个死循环
}
} //起六个线程
public static void main(String args[])
{
for(int i = 0; i < 6; i++)
new Thread(new CountTest(i+1)).start();
}
}如果注释掉
//if(++count== 6)
//return; 如果注释掉这两句,怎样结束这个死循环
这两句,我想达到结束这个死循环的效果,请问怎么实现?
高手指教!
public CountTest(int num)
{
number = num;
System.out.println("Create thread " + number);
} public void run()
{
while(true)
{
System.out.println("thread " + number + ":count " + count);
System.err.println(Thread.currentThread().toString());
//if(++count== 6)
//return; 如果注释掉这两句,怎样结束这个死循环
}
} //起六个线程
public static void main(String args[])
{
for(int i = 0; i < 6; i++)
new Thread(new CountTest(i+1)).start();
}
}如果注释掉
//if(++count== 6)
//return; 如果注释掉这两句,怎样结束这个死循环
这两句,我想达到结束这个死循环的效果,请问怎么实现?
高手指教!
启动时用:th.start();
结束时用:th.destory();
但是,并不提倡在外部使用destory来结束一个线程,这样不安全,也不会回收资源.
所以只有设置一个标志,然后在外部改变它.
public void run(){
while(needLoop){
System.out.println("thread " + number + ":count " + count);
System.err.println(Thread.currentThread().toString());
}
}
问题是,我想保证run()里的代码只能使这些:
while(true)
{
System.out.println("thread " + number + ":count " + count);
System.err.println(Thread.currentThread().toString()); }不能设置needLoop标志。
请大家再帮我想想办法吧!
在需要结束的的地方,比如在主线程里sleep(6000);stop=true;就可以了