从一道面试题分析Thread.interrupt方法

来源:互联网 发布:java资深工程师面试题 编辑:程序博客网 时间:2024/06/05 16:23
阿里面试题:

public class TestThread {public static void main(String[] args) {Thread t1 = new Thread() {@Overridepublic void run() {try {int i = 0;while (i++ < 100000000) {// nothing}System.out.println("A1");} catch (Exception e) {System.out.println("B2");}}};t1.start();t1.interrupt();Thread t2 = new Thread() {@Overridepublic void run() {try {Thread.sleep(5000);System.out.println("A2");} catch (Exception e) {System.out.println("B2");}}};t2.start();t2.interrupt();Thread t3 = new Thread() {@Overridepublic void run() {try {this.wait(5000);System.out.println("A3");} catch (Exception e) {System.out.println("B3");}}};t3.start();t3.interrupt();Thread t4 = new Thread() {@Overridepublic void run() {try {synchronized (this) {this.wait(5000);}System.out.println("A4");} catch (Exception e) {System.out.println("B4");}}};t4.start();t4.interrupt();try {t4.start();System.out.println("A5");} catch (Exception e) {System.out.println("B5");}}}
输出结果为

B2
B5
B3
B4
A1

在JDK1.0中,可以用stop方法来终止,但是现在这种方法已经被禁用了,改用interrupt方法。

Thread.interrupt()方法不会中断一个正在运行的线程。它的作用是,在线程受到阻塞时抛出一个中断信号,这样线程就得以退出阻塞的状态。更确切的说,如果线程被Object.wait, Thread.join和Thread.sleep三种方法之一阻塞,那么,它将接收到一个中断异常(InterruptedException),从而提早地终结被阻塞状态。

interrupt方法并不是强制终止线程,它只能设置线程的interrupted状态。

class StopThread implements Runnable {private boolean flag = true;public synchronized void run() {while (flag) {try {wait();} catch (InterruptedException e) {System.out.println(Thread.currentThread().getName() + "....Exception");flag = false;}System.out.println(Thread.currentThread().getName() + "....run");}}public void changeFlag() {flag = false;}}class MyStopThreadDemo {public static void main(String[] args) throws InterruptedException {StopThread st = new StopThread();Thread t1 = new Thread(st);Thread t2 = new Thread(st);t1.start();t2.start();Thread.sleep(100);int num = 0;while (true) {if (num++ == 60) {t1.interrupt();t2.interrupt();break;}System.out.println(Thread.currentThread().getName() + "......."+ num);}System.out.println("over");}}



0 0
原创粉丝点击