线程的终止

1.stop()方法(不建议使用)

  

 1 package XianChengFenXi;
 2 /*
 3  * 如何强行终止一个线程的执行
 4  */
 5 public class ThreadTest9 {
 6     
 7     public static void main(String[] args){
 8         Thread t=new Thread(new MyRunnable3());
 9         t.setName("t");
10         t.start();
11         
12         //模拟5秒睡眠
13         try {
14             Thread.sleep(1000*5);
15         } catch (InterruptedException e) {
16             // TODO Auto-generated catch block
17             e.printStackTrace();
18         }
19         
20         //5秒钟后强行终止t线程
21         t.stop(); //已过时,不建议使用
22         /*
23          * stop()方法存在的缺点:
24          * 容易丢数据,因为它是直接将线程关闭,线程没有保存的数据将会丢失
25          */
26     }
27 }
28 class MyRunnable3 implements Runnable{
29     public void run(){
30         for(int i=0;i<10;i++){
31             System.out.println(Thread.currentThread().getName()+"--------->"+i);
32             try {
33                 Thread.sleep(1000);
34             } catch (InterruptedException e) {
35                 // TODO Auto-generated catch block
36                 e.printStackTrace();
37             }
38         }
39     }
40     
41 }

2.

 1 package XianChengFenXi;
 2 
 3 
 4 /*
 5  * 合理地终止线程的进行
 6  */
 7 public class ThreadTest10 {
 8     
 9     public static void main(String[] args){
10         
11         MyRunnable4 mr4=new MyRunnable4();
12         Thread t=new Thread(mr4);
13         t.setName("t");
14         t.start();
15         
16         try {
17             Thread.sleep(1000*5);
18         } catch (InterruptedException e) {
19             // TODO Auto-generated catch block
20             e.printStackTrace();
21         }
22         mr4.run=false;
23         
24     }
25 
26 }
27 class MyRunnable4 implements Runnable{
28     boolean run=true;
29     public void run(){
30         for(int i=0;i<10;i++){
31             if(run){
32             System.out.println(Thread.currentThread().getName()+"--------->"+i);
33             try {
34                 Thread.sleep(1000);
35             } catch (InterruptedException e) {
36                 // TODO Auto-generated catch block
37                 e.printStackTrace();
38             }
39             }else {
40                 //在return之前可以编写代码,保存需要的信息
41                 return;
42             }
43         
44         }
45     }
46 }

 

posted @ 2020-10-17 13:43  L1998  阅读(126)  评论(0)    收藏  举报