为什么处于BLOCKED状态的线程不会被中断? [英] Why does Threads in BLOCKED state do not get interrupted?

查看:330
本文介绍了为什么处于BLOCKED状态的线程不会被中断?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很晚才开始在java中进行多线程处理。
想要了解Thread是否处于BLOCKED状态,为什么它不能被中断?为什么线程只有在处于WAIT状态时才能被中断?基本上,为什么我们需要两个Thread状态,一个可以被中断而另一个不能被中断?

Off late i am working on multithreading in java. Want to understand if a Thread is in BLOCKED state why it cant be interrupted? And why the thread can be interrupted only if it is in WAIT state? Basically, why do we need two Thread states one which can be interrupted and the other which cant be interrupted?

这个问题可能是非常基本的但是,我试图理解事情而不仅仅是记住它们。

This question might be very basic but, I am trying to understand things rather than just remembering them.

推荐答案

假设你的意思是让线程停止当前的操作并抛出 InterruptedException ? Java中的线程中断只是一个标志。您可以在BLOCKED线程上调用 interrupt()就好了,下次代码检查时会看到该标志。

One assumes that you mean cause the thread to stop its current operation and throw an InterruptedException? A thread interrupt in Java is just a flag. You can call interrupt() just fine on a BLOCKED thread and that flag will be seen next time code checks for it.

实现这样一个功能的主要问题是,关键字( synchronized )应该如何抛出异常? InterruptedException 是一个已检查的异常,必须使用语言声明每个同步的方法(和块)抛出InterruptedException

The principle problem with implementing such a functionality is, how is a keyword (synchronized) supposed to throw an exception? InterruptedException is a checked exception, it would not be a useful exercise to have to declare every synchronized method (and block) in the language with throws InterruptedException!

中断是一种通信工具,它通常用于让线程知道它需要检查的系统状态。该名称是从硬件中设置的标志进行遗留/向上传输,以便让微处理器了解需要检查的特定状态(例如在某些输入引脚上设置的新值)。不要过多地读入名称interrupt,并认为它是一个打破另一个线程中程序流的工具。它不是。因此,即使抛出异常的方法也将其声明为已检查,另一个线程可以自由地忽略它并在需要时继续等待。能够任意破坏另一个线程的 BLOCKED 状态会破坏程序流程,这不是目的。

An interrupt is a communication tool, it's generally for letting a thread know about a system state it needs to check on. The name is a legacy carry over/upward from flags set within hardware to let microprocessors know about a particular state (such as new values set on some input pins) that needs to be examined. Do not read too much into the name "interrupt" and think it's meant to be a tool for breaking the flow of the program within another thread. It is not. Hence even the methods that do throw an exception declare it as checked, the other thread is free to ignore it and resume waiting if it wants. Being able to arbitrarily break another thread's BLOCKED state would break the program flow, which is not the purpose.

这篇关于为什么处于BLOCKED状态的线程不会被中断?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆