Java Thread Interrupt


线程,是编程中处理并发最常用的方式。但是如果用不好,也是一个比较麻烦的事情。毕竟创建一个线程是件容易的事情。但是怎么终止一个线程,却不那么容易。关于线程的退出,最好的方式当然是让线程处理完相应的工作后自动退出。其次是主线程有效的通知到工作线程,“Hello, please exit!”。当然,暴力终止是不被推荐的,可能会发生数据一致性的问题。或者,其他未知问题。

我首先能想到的通知一个线程中断,就是设置线程中断标志。

import java.io.IOException;
import java.net.ServerSocket;

public class InterruptTest {

    private static boolean interrupt = false;
    
    public static boolean getInterrupt(){
        return interrupt;
    }
    
    public synchronized static void setInterupt(boolean value){
        interrupt = value;
    }
    
    public void method1(){
        try{
            int i=1;
            while(!interrupt){
                System.out.println("thread continue excute " + i++);
            }
        }catch(Exception e){
            System.out.println(e.getMessage());
        }
    }
    
    public static void main(String args[]) throws InterruptedException, IOException{
        InterruptTest test = new InterruptTest();
        
        Thread thread = new Thread(new Runnable(){

            @Override
            public void run() {
                test.method1();
            }
            
        });
        
        thread.start();
        Thread.sleep(2000);
                InterruptTest.setInterupt(true);
        thread.join();
        
        System.out.println("Main thread finished!");
    }
}

这种方式当然可以有效的通知一直有任务运行的线程去中断自己。但是,如果线程一直处于阻塞状态,比如Thread.sleep()。显然线程是无法及时获取中断标志的。考虑下面这种场景。这个时候就该Thread.interrupt出场了。

import java.io.IOException;
import java.net.ServerSocket;

public class InterruptTest {

    private static boolean interrupt = false;
    public static boolean getInterrupt(){
        return interrupt;
    }
    
    public synchronized static void setInterupt(boolean value){
        interrupt = value;
    }
    
    public void method1(){
        try{
            int i=1;
            while(!interrupt){
                System.out.println("thread continue excute " + i++);
            }
        }catch(Exception e){
            System.out.println(e.getMessage());
        }
    }
    
    public void method2(){
        try{
            int i=1;
            while(!interrupt){
                System.out.println("thread continue excute " + i++);
                Thread.sleep(3000);
                
            }
        }catch(Exception e){
            setInterupt(true);
            System.out.println(e.getMessage());
        }
    }
    
    public static void main(String args[]) throws InterruptedException, IOException{
        InterruptTest test = new InterruptTest();
        
        Thread thread = new Thread(new Runnable(){

            @Override
            public void run() {
                test.method2();
            }
            
        });
        
        thread.start();
        Thread.sleep(2000);
        thread.interrupt();
        thread.join();
        
        System.out.println("Main thread finished!");
    }
}

输出结果为:

thread continue excute 1
sleep interrupted
Main thread finished!

Thread.sleep函数导致线程阻塞。interrput函数会发送一个java.lang.InterruptedException异常,当线程捕获这个异常就会通知线程终止循环。
但调用interrupt函数也仅仅只能让能接收InterruptedException异常的阻塞终止。其他一些I/O阻塞是不会理会interrupt函数发出的异常的。这种情况就需要针对不同的情况做处理了。比如,socket阻塞在accpet函数。interrupt函数就无能为力了。这时候就可以通过socket的close函数来关闭端口。

import java.io.IOException;
import java.net.ServerSocket;

public class InterruptTest {

    private static boolean interrupt = false;
    private ServerSocket socket1;
    
    public ServerSocket getSocket(){
        return socket1;
    }
    
    public static boolean getInterrupt(){
        return interrupt;
    }
    
    public synchronized static void setInterupt(boolean value){
        interrupt = value;
    }
    
    public void method1(){
        try{
            int i=1;
            while(!interrupt){
                System.out.println("thread continue excute " + i++);
            }
        }catch(Exception e){
            System.out.println(e.getMessage());
        }
    }
    
    public void method2(){
        try{
            int i=1;
            while(!interrupt){
                System.out.println("thread continue excute " + i++);
                Thread.sleep(3000);
                
            }
        }catch(Exception e){
            setInterupt(true);
            e.printStackTrace();
        }
    }
    
    public void method3(){
        try{

            System.out.println("Start to run thread!");
            socket1 = new ServerSocket(8889);
            socket1.accept();
            System.out.println("Setup one connection!");
                
        }catch(Exception e){
            setInterupt(true);
            System.out.println(e.getMessage());
        }
    }
    
    public static void main(String args[]) throws InterruptedException, IOException{
        InterruptTest test = new InterruptTest();
        
        Thread thread = new Thread(new Runnable(){

            @Override
            public void run() {
                test.method3();
            }
            
        });
        
        thread.start();
        Thread.sleep(2000);
        test.getSocket().close();
        thread.join();
        
        System.out.println("Main thread finished!");
    }
}

输出结果:

Start to run thread!
socket closed
Main thread finished!

其实在调用Socket.close函数的时候,socket线程会接收到一个java.net.SocketException异常。然后通过捕获这个异常,改变线程中断标志来中断线程。

总之,如何有效的中断一个线程。需要根据实际情况来处理。换到风险投资领域。进入之前就先想好退出方式。如果你的工作线程没有阻塞,就用中断标志控制就好。如果有一般阻塞,准备好处理interruptedException。如果有其他I/O阻塞,先提供阻塞对象的句柄获取方式。然后准备好处理相应的中断异常。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 一、并发 进程:每个进程都拥有自己的一套变量 线程:线程之间共享数据 1.线程 Java中为多线程任务提供了很多的...
    SeanMa阅读 7,382评论 0 11
  • 取消原因 取消一个任务执行的理由有很多,通常有以下几个 用户请求取消通常用户点击“取消”按钮发出取消命令 有时间限...
    德彪阅读 6,177评论 0 2
  • 下面是我自己收集整理的Java线程相关的面试题,可以用它来好好准备面试。 参考文档:-《Java核心技术 卷一》-...
    阿呆变Geek阅读 14,998评论 14 507
  • 本文主要讲了java中多线程的使用方法、线程同步、线程数据传递、线程状态及相应的一些线程函数用法、概述等。 首先讲...
    李欣阳阅读 7,188评论 1 15
  • 一、多线程 说明下线程的状态 java中的线程一共有 5 种状态。 NEW:这种情况指的是,通过 New 关键字创...
    Java旅行者阅读 10,179评论 0 44