利用方法终止一个循环线程:
(1)利用bool值的设置控制线程的执行与否
(2)利用interruput方法终止含有wait的循环线程;
public class test {
public static void main(String[] args)
{
Product p=new Product();
p.start();
int index=0;
while(true)
{
if(index++==500)
{
p.getstop();
p.interrupt();
break;
}
System.out.println(Thread.currentThread().getName());
}
System.out.println(Thread.currentThread().getName()+" exit");
}
}
class Product extends Thread{
private boolean b=false;
public synchronized void run()
{
while(!b)
{
try
{
wait();
}
catch(Exception e)
{
if(b)
return;
}
System.out.println(getName()+"product");
}
}
public void getstop()
{
b=true;
}
}
多线程(四)循环线程的终止
最新推荐文章于 2023-06-19 14:13:33 发布