美文网首页
Java 中断线程

Java 中断线程

作者: 西贝巴巴 | 来源:发表于2021-03-16 09:40 被阅读0次
package com.company;

/*
使用interrupt()方法来中断线程并使用 isInterrupted() 方法来判断线程是否已中断
*/
public class InterruptTest extends Object implements Runnable {
    @Override
    public void run() {
        try {
            System.out.println("in run() - 将运行 work2() 方法");
            work2();
            System.out.println("in run() - 从 work2() 方法回来");

        } catch (InterruptedException e) {
            System.out.println("in run() - 中断 work2() 方法");
            return;
        }
        System.out.println("in run() - 休眠后执行");
        System.out.println("in run() - 正常离开");

    }

    public void work2() throws InterruptedException {
        while (true) {
            if (Thread.currentThread().isInterrupted()) {
                System.out.println("C isInterrupted()=" + Thread.currentThread().isInterrupted());
                Thread.sleep(2000);
                System.out.println("D isInterrupted()=" + Thread.currentThread().isInterrupted());
            }
        }
    }

    public void work() throws InterruptedException {
        while (true) {
            for (int i = 0; i < 100000; i++) {
                int j = i * 2;
            }
            System.out.println("A isInterrupted()=" + Thread.currentThread().isInterrupted());
            if (Thread.interrupted()) {
                System.out.println("B isInterrupted()=" + Thread.currentThread().isInterrupted());
                throw new InterruptedException();
            }
        }
    }

    public static void main(String[] args) {
        InterruptTest i = new InterruptTest();
        Thread t = new Thread(i);
        t.start();
        try {
            Thread.sleep(2000);
        } catch (InterruptedException x) {
        }
        System.out.println("in main() - 中断其他线程");
        t.interrupt();
        System.out.println("in main() - 离开");
    }
}



相关文章

  • Java线程中断

    本文主要介绍Java线程中断一些相关的概念以及注意点 Java线程的中断并不是强制的中断,调用线程中断的方法时只是...

  • 线程中断

    什么是线程中断?线程中断即线程运行过程中被其他线程打断了。 线程中断的重要方法2.1 java.lang.Thre...

  • JAVA并发编程(三)线程协作与共享

    1. 线程中断 java线程中断是协作式,而非抢占式 1.1. 线程中断相关方法 interrupt()将线程的中...

  • 【多线程】——3.线程的中断

    线程中断的概念 java线程中断是一种协作机制 通过中断并不能直接终止线程的运行 需要被中断的线程自己处理中断 (...

  • (4)线程中断

    什么是线程中断 java中的线程中断并不是指强制线程中断执行,而是指调用线程中断起到一个通知作用,让线程知道自己被...

  • 线程中断

    Java的中断是一种协作机制,线程中断不会终止线程的运行,但是可以通过线程中断来实现终止线程运行。 线程在不同状态...

  • Java “优雅”地中断线程(原理篇)

    前言 线程中断系列文章: Java “优雅”地中断线程(实践篇)[https://www.jianshu.com/...

  • Java线程中断

    首先,一个线程不应该由其他线程来强制中断或停止,而是应该由线程自己自行停止。所以,Thread.stop, Thr...

  • Java 线程中断

    1. 中断线程 public void interrupt()停止一个线程,但不会终止一个正在运行的,还需要加入一...

  • Java线程简介

    本文将介绍Java线程的状态、线程的中断、线程间通信和线程的实现。 线程的状态 Java语言定义了6种不同的线程状...

网友评论

      本文标题:Java 中断线程

      本文链接:https://www.haomeiwen.com/subject/jtlcqltx.html