首页 > 其他 > 详细

停止线程方式

时间:2014-03-01 20:10:10      阅读:553      评论:0      收藏:0      [点我收藏+]

停止线程方法_stop方法(已过时)

 

停止线程方法_定义标记(run方法结束)

怎么控制线程的任务结束:

  线程任务中都会有循环结构,只要控制住循环就可以结束任务。控制循环通常就用定义标记来完成。

bubuko.com,布布扣
 1 class StopThread implements Runnable{
 2     private boolean flag = true;
 3     public void run(){
 4         while(flag){
 5             System.out.println(Thread.currentThread().getName()+".....");
 6         }
 7     }
 8     public void setFlag(){
 9         flag = false;
10     }
11 }
12 class StopThreadDemo {
13     public static void main(String[] args) {
14         StopThread st = new StopThread();
15 
16         Thread t1 = new Thread(st);
17         Thread t2 = new Thread(st);
18 
19         t1.start(); 
       t2.start();
22 
23 
24         int num = 1;
25         for(;;){
26             if(++num==50){
27                 st.setFlag();
28                 break;
29             }
30             System.out.println("main...."+num);
31         }
32         System.out.println("over");
33     }
34 }
bubuko.com,布布扣

 

但是如果线程处于了冻结状态,无法读取标记。如何结束:

    可以使用Thread类中的interrupt()方法将线程从冻结状态强制恢复到运行状态中来,让线程具备cpu的执行资格。

    因为强制动作会发生了InterruptedException,记得要处理,在catch中处理的时候 将标记改为false就可以结束循环,线程也就结束了

bubuko.com,布布扣
 1 class StopThread implements Runnable{
 2     private boolean flag = true;
 3     public synchronized void run(){
 4         while(flag){
 5             try{
 6                 wait();//t0 t1    使用这个方法是强制性唤醒的会发生异常,就执行catch里的代码,然后将标记改为false
 7             }catch (InterruptedException e){
 8                 System.out.println(Thread.currentThread().getName()+"....."+e);
 9                 flag = false;
10             }
11             
12             System.out.println(Thread.currentThread().getName()+"......++++");
13         }
14     }
15     public void setFlag(){
16         flag = false;
17     }
18 }
19 class StopThreadDemo {
20     public static void main(String[] args) {
21         StopThread st = new StopThread();
22 
23         Thread t1 = new Thread(st);
24         Thread t2 = new Thread(st);
25 
26         t1.start();
27         t2.start();
29 
30 
31         int num = 1;
32         for(;;){
33             if(++num==50){
34                 t1.interrupt();
35                 t2.interrupt();
36                 break;
37             }
38             System.out.println("main...."+num);
39         }
40         System.out.println("over");
41     }
42 }
bubuko.com,布布扣

停止线程方式,布布扣,bubuko.com

停止线程方式

原文:http://www.cnblogs.com/LO-ME/p/3574608.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!