怎么终止线程的执行
1.强制终止
stop()方法
缺点:强制终止会丢数据
不建议使用
public class myfile{
@SuppressWarnings("deprecation")
public static void main(String[] args) {
Thread t=new Thread(new myrunnable());
t.setName("ttt");
t.start();
try{
Thread.sleep(1000*5);
}catch(InterruptedException e){
e.printStackTrace();
}
//5秒后终止线程
t.stop();//(已过时,强制终止会丢数据)
}
}
class myrunnable implements Runnable{
//run()方法当中的异常不能throws,只能try catch
//因为run()方法在父类没有抛出任何异常,子类不能比父类抛出更多的异常
@Override
public void run() {
for(int i=0;i<10;i++)
System.out.println(Thread.currentThread().getName()+"-->"+i);
try{
Thread.sleep(1000*1);
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
不过,我的代码好像没有成功
ttt–>0
ttt–>1
ttt–>2
ttt–>3
ttt–>4
ttt–>5
ttt–>6
ttt–>7
ttt–>8
ttt–>9
但是确实有这个方法可以强制终止线程的执行
2.怎么合理终止线程执行
利用boolean设置标记,为true时执行代码,否则终止
public class a1{
public static void main(String[] args) {
Thread t=new Thread(new myrunnable());
t.setName("ttt");
t.start();
try{
Thread.sleep(1000*5);
}catch(InterruptedException e){
e.printStackTrace();
}
//5秒后终止线程
//将标记设为false
t.run0=false;
}
}
class myrunnable implements Runnable{
//run()方法当中的异常不能throws,只能try catch
//因为run()方法在父类没有抛出任何异常,子类不能比父类抛出更多的异常
boolean run0=true;
@Override
public void run() {
for(int i=0;i<10;i++){
if(run0){
System.out.println(Thread.currentThread().getName()+"-->"+i);
try{
Thread.sleep(1000*1);
}catch(InterruptedException e){
e.printStackTrace();
}
}
else
//终止线程
return;
}
}
}