📜  在Java中中断线程

📅  最后修改于: 2022-05-13 01:54:56.974000             🧑  作者: Mango

在Java中中断线程

在Java Threads 中,如果任何线程处于睡眠或等待状态(即调用sleep() 或wait()),调用该线程的interrupt() 方法,会打破睡眠或等待状态并抛出InterruptedException。如果线程不处于睡眠或等待状态,调用interrupt() 方法执行正常行为并且不中断线程但将中断标志设置为true。

interrupt() 方法:如果任何线程处于睡眠或等待状态,那么使用interrupt() 方法,我们可以通过显示InterruptedException 来中断该线程的执行。处于睡眠或等待状态的线程可以借助 Thread 类的 interrupt() 方法被中断。

示例:假设有两个线程,如果其中一个线程在调用 Object 类或 join() 的 wait()、wait(long) 或 wait(long, int) 方法时被阻塞,则加入(long), join(long, int), sleep(long), or sleep(long, int),这个类的方法,然后它的中断状态将被清除,它会收到一个InterruptedException,这给了另一个线程机会执行另一个线程的相应 run() 方法,从而提高性能并减少线程的等待时间。

我们可以中断线程的不同场景

案例1:中断一个不停止工作的线程:在程序中,我们使用try和catch块来处理InterruptedException,所以每当任何线程中断当前正在执行的线程时,它都会从睡眠状态中出来,但不会停止工作.

Java
// Java Program to illustrate the
// concept of interrupt() method
// while a thread does not stops working
  
class MyClass extends Thread {
    public void run()
    {
        try {
            for (int i = 0; i < 5; i++) {
                System.out.println("Child Thread executing");
  
                // Here current threads goes to sleeping state
                // Another thread gets the chance to execute
                Thread.sleep(1000);
            }
        }
        catch (InterruptedException e) {
            System.out.println("InterruptedException occur");
        }
    }
}
  
class Test {
    public static void main(String[] args)
            throws InterruptedException
    {
        MyClass thread = new MyClass();
        thread.start();
  
        // main thread calls interrupt() method on
        // child thread
        thread.interrupt();
  
        System.out.println("Main thread execution completes");
    }
}


Java
// Java Program to illustrate the
// concept of interrupt() method
// while a thread stops working
  
class Geeks extends Thread {
    public void run()
    {
        try {
            Thread.sleep(2000);
            System.out.println("Geeksforgeeks");
        }
        catch (InterruptedException e) {
            throw new RuntimeException("Thread " +
                                    "interrupted");
        }
    }
    public static void main(String args[])
    {
        Geeks t1 = new Geeks();
        t1.start();
        try {
            t1.interrupt();
        }
        catch (Exception e) {
            System.out.println("Exception handled");
        }
    }
}


Java
// Java Program to illustrate the concept of
// interrupt() method
  
class Geeks extends Thread {
    public void run()
    {
        for (int i = 0; i < 5; i++)
            System.out.println(i);
    }
    public static void main(String args[])
    {
        Geeks t1 = new Geeks();
        t1.start();
        t1.interrupt();
    }
}


输出
Main thread execution completes
Child Thread executing
InterruptedException occur

案例2:中断一个停止工作的线程:在程序中,在中断当前正在执行的线程之后,我们在catch块中抛出一个新的异常,使其停止工作。

Java

// Java Program to illustrate the
// concept of interrupt() method
// while a thread stops working
  
class Geeks extends Thread {
    public void run()
    {
        try {
            Thread.sleep(2000);
            System.out.println("Geeksforgeeks");
        }
        catch (InterruptedException e) {
            throw new RuntimeException("Thread " +
                                    "interrupted");
        }
    }
    public static void main(String args[])
    {
        Geeks t1 = new Geeks();
        t1.start();
        try {
            t1.interrupt();
        }
        catch (Exception e) {
            System.out.println("Exception handled");
        }
    }
}

输出

Exception in thread "Thread-0" java.lang.RuntimeException: Thread interrupted
    at Geeks.run(File.java:13)

案例3:中断一个正常工作的线程:在程序中,线程执行过程中没有发生异常。这里interrupt只是将interrupted标志设置为true,供Java程序员以后使用。

Java

// Java Program to illustrate the concept of
// interrupt() method
  
class Geeks extends Thread {
    public void run()
    {
        for (int i = 0; i < 5; i++)
            System.out.println(i);
    }
    public static void main(String args[])
    {
        Geeks t1 = new Geeks();
        t1.start();
        t1.interrupt();
    }
}
输出
0
1
2
3
4