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阻塞,先提供阻塞对象的句柄获取方式。然后准备好处理相应的中断异常。

你可能感兴趣的:(Java Thread Interrupt)