首页 > Java > java教程 > 正文

Java 中断异常

WBOY
发布: 2024-08-30 16:15:01
原创
895 人浏览过

当线程在执行某些活动之前或执行时可能正在休眠、等待或被占用和中断时,会发生 InterruptedException。有时,方法可能想要测试当前线程是否已被中断。如果它被中断,那么它将立即抛出异常。否则,它将按照原来的方式工作。在本主题中,我们将学习 Java InterruptedException。

开始您的免费软件开发课程

网络开发、编程语言、软件测试及其他

语法

为了使用异常,您必须使用以下语法:

if (Thread.interrupted ())  // Clears interrupted status!
throw new InterruptedException ();
登录后复制

这里InterruptedException()方法创建了一个InterruptedException,其中没有详细消息作为参数。

但是如果它像 InterruptedException (String s) 一样抛出,它会创建一个带有一些特定细节的 InterruptedException。在此方法中,s 是详细消息。

InterruptedException 在 Java 中如何工作?

这里我们讨论InterruptedException的工作流程。在多线程代码中,线程经常会阻塞;线程暂停执行,直到满足某些外部条件,例如:

  • 当锁被释放时
  • 或另一个线程完成操作
  • 并且一些 I/O 操作完成

在这里,线程可以被中断。当中断发生时,它会阻止线程执行它们正在执行的常规工作。但对指定中断的确切响应取决于线程的状态以及线程的实现方式,如下所示:

我们将有一个线程,可用于阻止线程或较早存在的线程。当它被捕获时,它会抛出 InterruptedException。如果没有问题并且没有较早的线程,则该线程将继续其工作。当线程遇到异常时,它将线程的中断状态设置为 true。线程会定期轮询方法checkInterrupted()。这是线程预期工作的首选方式。该过程完成后,就会发生清理活动。清理完毕后,停止执行。如果有的话,它会抛出 InterruptedException,如果没有,它会继续正常的执行流程。

如果上述过程中出现中断,该过程不应该立即关闭线程。这是因为它将处于某些计算的中间,而计算总是会发生,因此它必须等待。

构造函数

构造函数是 Java 对象,有助于初始化新创建的对象或方法。它是一个没有任何返回类型的 Java 实例。由于这应该初始化对象,因此它与其所属的类具有相同的名称。因此,每当调用该对象时,都会自动调用构造函数并进行初始化。下面是一个构造方法。

InterruptedException ()
登录后复制

这里,这个方法创建了一个没有消息的异常。此处正在创建 InterruptedException 类的实例。在此构造函数中,消息参数被设置为 null。

示例:

public InterruptedException () InterruptedException (String s)
登录后复制

在InterruptedException类的这个方法中,参数被用作字符串格式的指定消息。这里的字符串参数解释了引发错误的类的名称。

InterruptedException 示例

现在我们将看一个线程被中断的示例:

// Java Program to check how
// interrupt () method  works
// simultaneously while a thread stops working
class CheckInterruption extends Thread {
public void run ()
{
try {
Thread.sleep (2000);
System.out.println ( "We are checking Interrupted Exception");
}
catch (InterruptedException e) {
throw new RuntimeException ( "Thread is" + "interrupted");
}
}
public static void main (String args[])
{
CheckInterruption t1 = new CheckInterruption ();
t1.start ();
try {
t1.interrupt ();
}
catch (Exception e) {
System.out.println ("Exception handled");
}
}
}
登录后复制

输出:

Java 中断异常

上面的代码帮助我们理解中断异常的概念。我们有一个类,CheckInterruption,它扩展了 Java 的 Thread 类。然后它在 try 块中查找异常。如果存在异常,则会在 catch 块中捕获该异常,并将输出显示为 catch 块。在我们的示例中就是这种情况,捕获了中断,并显示了必要的输出。但程序并未完成,因为 catch 块调用了 Java 中存在的 Exception() 方法。现在让我们检查一个示例,其中捕获了异常,然后启动下一个线程。

class CheckInterruptingThread2 extends Thread{
public void run (){
try{  Thread.sleep (1000);
System.out.println ("task");
}catch (InterruptedException e){
System.out.println ("Exception is handled "+e);  }
System.out.println ("thread is now in running state...");
}
public static void main (String args[]){
CheckInterruptingThread2 t1=new CheckInterruptingThread2 ();
t1.start ();
t1.interrupt ();
}
}
登录后复制

输出:

Java 中断异常

The above program uses a class that is again extending the Thread class in Java. In the try () block, we make the thread sleep for some time, and then the catch block catches the exception when it is encountered. Once it is handled, the message is printed, and then the interrupt () method is called, after which the next thread moves to the running state. The same is displayed after the method call is finished and the thread starts working.

How to avoid InterruptedException?

The solution to this exception is you can stop making use of thread.sleep () method. Instead of this method, the more efficient method will be SystemClock.sleep () method. Another replacement for the above-mentioned method can be using TimeCOunter, which will depend on the logic and code where it is being used. This can also be an optimal solution.

If at all you would still like to make use of thread.sleep () then it should be used as below.

try {
Thread.sleep ();
} catch (InterruptedException e) {
Thread.currentThread ().interrupt (); /* this line will see to it that Thread.interrupted () always returns true */
throw new RuntimeException (e);
}
登录后复制

Conclusion – Java InterruptedException

As the word exception suggests, it is a state which can be checked and allowed to pass in some cases. InterruptedException happens when a thread waits or sleeps, and other threads are interrupted and cannot proceed further. We can handle this exception by either using proper try-catch blocks or by avoiding the usage of the sleep () method.

以上是Java 中断异常的详细内容。更多信息请关注PHP中文网其他相关文章!

相关标签:
来源:php
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!