Java多线程之线程中止

栏目: Java · 发布时间: 8年前

内容简介:Java多线程之线程中止

shop()

Java中提供了shop()方法来中断线程,但其过于暴力而被定义为过期方法。假如一条线程在修改一段数据时,且已经修改了一半,此时的你强行用shop()方法中断该线程后,数据处于一半修改过、一半未修改的状态,该数据就已经废了(且不会有任何提示)。除非你清楚在干什么,否则不要使用shop()。

Java中推荐使用中断:

public void Thread.interrupt() //中断线程

public boolean Thread.isInterrupted()    //判断是否被中断

public static boolean Thread.interrupted()    //判断是否被中断,且清除当前中断状态

public static void main(String[] args) throws InterruptedException {
    Thread t1 = new Thread() {
    @Override
    public void run () {
        while (true) {
        Thread.yield();
        }
    }
};
    t1.start();
    Thread.sleep(2000);
    ti.interrupt();
}

在这里虽然调用了interrupt()方法,但该线程并不会停下。因为该方法只是设置了一个中断状态,但该线程并未对此中断状态做出反应。

以下代码进行了对中断状态的处理。

public static void main(String[] args) throws InterruptedException {
    Thread t1 = new Thread() {
    @Override
    public void run () {
        while (true) {
            if (Thread.currentThread().isInterrupted()){     //此方法返回中断状态,且不会清除该中断状态。
            System.out.println("Interruted!");
            breadk;
            }
            Thread.yield();
        }
    }
};
    t1.start();
    Thread.sleep(2000);
    ti.interrupt();
}

但我们使用wait() 或者 sleep() 方法时要注意下:

首先得了解下Thread.sleep()函数:

public static native void sleep(long millis) throws InterruptedException

当该线程休眠时如果中断则会抛出该错误,此异常非运行时异常,必须捕获且处理。

public static void main(String[] args) throws InterruptedException {
    Thread t1 = new Thread() {
    @Override
    public void run () {
        while (true) {
            if (Thread.currentThread().isInterrupted()){
            //此方法返回中断状态,且不会清除该中断状态
            System.out.println("Interruted!");
            break;
            }
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                System.out.println("Interruted When Sleep");
                // 设置中断状态
                Thread.currentThread().interrupt();
            }
        Thread.yield();
        }
    }
};
    t1.start();
    Thread.sleep(2000);
    t1.interrupt();
}

在catch语块中本可以进行中断退出,但我们没这么做,因为这样会破坏数据一致性和完整性(和直接使用shop()用异曲同工之妙)。所以我们在异常处理中必须重新设置中断状态(因为此时抛出异常后状态会被清除),让该线程完成工作后再退出。


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Sovereign Individual

The Sovereign Individual

James Dale Davidson、William Rees-Mogg / Free Press / 1999-08-26 / USD 16.00

Two renowned investment advisors and authors of the bestseller The Great Reckoning bring to light both currents of disaster and the potential for prosperity and renewal in the face of radical changes ......一起来看看 《The Sovereign Individual》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换