Java Thread interrupt()方法

java.lang.Thread.interrupt() 方法中断这个线程。中断一个线程,是不是活着不会有任何影响。

1 语法

public void interrupt()

2 参数

3 返回值

4 示例 

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * java.lang.Thread.interrupt()方法的例子
 */
import java.lang.*;

public class Demo implements Runnable {

    Thread t;

    Demo() {

        t = new Thread(this);
        System.out.println("Executing " + t.getName());

        // this will call run() fucntion
        t.start();

        // interrupt the threads
        if (!t.interrupted()) {
            t.interrupt();
        }

        // block until other threads finish
        try {
            t.join();
        } catch(InterruptedException e) {}
    }

    public void run() {
        try {
            while (true) {
                Thread.sleep(1000);
            }
        } catch (InterruptedException e) {
            System.out.print(t.getName() + " interrupted:");
            System.out.println(e.toString());
        }
    }

    public static void main(String args[]) {
        new Demo();
        new Demo();
    }
}

输出结果为:

Executing Thread-0
Thread-0 interrupted:java.lang.InterruptedException: sleep interrupted
Executing Thread-1
Thread-1 interrupted:java.lang.InterruptedException: sleep interrupted

热门文章

优秀文章