Java中终止某个线程的方法

Java中终止某个线程的方法

在Java中有专门终止某个线程的API,如stop()和interrupt()。其中stop()由于安全机制的我问题已经被废弃不用,现在就剩下interrupt。其实这个方法并不是一个终断动作的操作,而是一个设置终断状态的操作。它需要和isInterrupted()配合使用。例如:

package org.itcast;  
public class MyThread04 extends Thread {  

    private boolean stop = false;  
    public MyThread04(String threadName) {  
        super(threadName);  
    }  

    @Override 
    public void run() {  

        for (int j = 0; j < 100; j++) {  
            if(this.isInterrupted()) break;  
            System.out.println(Thread.currentThread().getName()+":"+j);  
            try {  
                Thread.sleep(1000);  
            } catch (InterruptedException e) {  
                e.printStackTrace();  
            }  
        }  

    }  

    public void setStop() {  
        this.stop = true;  
    }  

    //第一个线程  
    public static void main(String[] args) {  
        MyThread04 t = new MyThread04("辅线程");  
        t.start();  

        for (int i = 0; i < 10; i++) {  
            System.out.println(Thread.currentThread().getName()+":"+i);  
        }  
        System.out.println("....................");  
        t.interrupt();  

    }  
}  

但这个很可能不会终止线程,因为当我们终止这个线程时很可能就会发生InterruptedException异常,当有这个异常发生时我们设置的终断状态也会被清除,所以我们要终断某个线程应采用以下这个方法:


package org.itcast;  

public class MyThread04 extends Thread {  

    private boolean stop = false;  
    public MyThread04(String threadName) {  
        super(threadName);  
    }  

    @Override 
    public void run() {  

        for (int j = 0; j < 100; j++) {  
            if(stop) break;  
            System.out.println(Thread.currentThread().getName()+":"+j);  
            try {  
                Thread.sleep(1000);  
            } catch (InterruptedException e) {  
                e.printStackTrace();  
            }  
        }  

    }  

    public void setStop() {  
        this.stop = true;  
    }  

    //第一个线程  
    public static void main(String[] args) {  
        MyThread04 t = new MyThread04("辅线程");  
        t.start();  

        for (int i = 0; i < 10; i++) {  
            System.out.println(Thread.currentThread().getName()+":"+i);  
        }  
        System.out.println("....................");  
        t.setStop();  
    }  
}  

通过设置一个我们自己的标识来达到终端某个线程。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值