JAVA-基础语法-多线程基础-中断线程

网友投稿 513 2022-05-29

中断线程

注意:此处的 Thread.sleep 对应的是主线程,而不是在执行的线程

public class InterruptThread {

public static void main(String[] args) throws InterruptedException {

Thread t = new MyThread();

t.start();

Thread.sleep(1); // 主线程暂停1毫秒

t.interrupt(); // 中断t线程

t.join(); // 等待t线程结束

JAVA-基础语法-多线程基础-中断线程

System.out.println("end");

}

}

class MyThread extends Thread {

public void run() {

int n = 0;

while (! isInterrupted()) {

n ++;

System.out.println(n + " hello!");

}

}

}

如果线程处于等待中,发起interrupt请求会如何?

public class Main {

public static void main(String[] args) throws InterruptedException {

Thread t = new MyThread();

t.start();

Thread.sleep(1000);

t.interrupt(); // 中断t线程

t.join(); // 等待t线程结束

System.out.println("end");

}

}

class MyThread extends Thread {

public void run() {

Thread hello = new HelloThread();

hello.start(); // 启动hello线程

try {

hello.join(); // 等待hello线程结束

} catch (InterruptedException e) {

System.out.println("interrupted!");

}

hello.interrupt();

}

}

class HelloThread extends Thread {

public void run() {

int n = 0;

while (!isInterrupted()) {

n++;

System.out.println(n + " hello!");

try {

Thread.sleep(100);

} catch (InterruptedException e) {

break;

}

}

}

}

main线程通过调用t.interrupt()从而通知t线程中断,而此时t线程正位于hello.join()的等待中,此方法会立刻结束等待并抛出InterruptedException。由于我们在t线程中捕获了InterruptedException,因此,就可以准备结束该线程。在t线程结束前,对hello线程也进行了interrupt()调用通知其中断。如果去掉这一行代码,可以发现hello线程仍然会继续运行,且JVM不会退出。

设置标志位

public class Main {

public static void main(String[] args)  throws InterruptedException {

HelloThread t = new HelloThread();

t.start();

Thread.sleep(1);

t.running = false; // 标志位置为false

}

}

class HelloThread extends Thread {

public volatile boolean running = true;

public void run() {

int n = 0;

while (running) {

n ++;

System.out.println(n + " hello!");

}

System.out.println("end!");

}

}

注意到HelloThread的标志位boolean running是一个线程间共享的变量。线程间共享变量需要使用volatile关键字标记,确保每个线程都能读取到更新后的变量值。

Java

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:多线程程序开发简介
下一篇:容器化上云之容器网络分析
相关文章