在被中断方法中断之前,java中的线程是否必须处于就绪状态? 我试图通过在下面键入上面给出的代码来检查这一点.
Is it necessary for a thread in java to be in ready state before it gets interrupted by interrupt method? I tried to check this by typing the above given code below.
class MyThread extends Thread { public void run() { try { for(int i =0;i<10;i++) { System.out.println("I am lazy thread"); Thread.sleep(2000); } } catch(InterruptedException e) { System.out.println("I got interrupted"); } } } public class SleepAndInterruptDemonstrationByDurga { public static void main(String[] args) { MyThread t= new MyThread(); t.start(); t.interrupt(); System.out.println("End of main thread"); } }即使尝试了多次,我得到的输出也总是低于1.
The output what I got was always was the below one even after trying many times
End of main thread I am lazy thread I got interrupted为什么不能输出
I am lazy thread I got interrupted End of main thread根据代码可以看出,中断方法首先由主线程调用.最终我想问在线程启动之前首先执行中断调用时有什么可能的情况吗?
as according to the code it can be seen that the interrupt method is called first by the main thread. Ultimately I want to ask that are there any situations possible when at first the interrupt call is executed before the the thread got started?
推荐答案这是怎么回事
1)您启动的线程需要时间才能准备好运行,因此主线程结束"可能会首先打印出来,尽管不能保证.
1) the thread you start needs time to get ready to run, so "end of main thread" is probably going to print first, though that’s not guaranteed.
2)在新线程完成启动之前设置了中断标志,但是直到线程休眠后,才会检查该标志的状态.当您在仅设置标志的线程上调用中断时,该线程不会做任何响应,除非您调用了sleep或isInterrupted之类的东西.因此,我被打扰"之前会显示我很懒".
2) the interrupt flag is set before the new thread is done starting, but nothing checks the status of that flag until the thread sleeps. When you call interrupt on a thread that only sets the flag, the thread doesn’t do anything to respond unless you put in calls to things like sleep or isInterrupted. So "I am lazy Thread" will show up before "I got interrupted".
中断是自愿的,需要被中断线程的配合.线程在运行之前无法对中断标志状态进行操作,因为某些代码必须检查该标志并对其进行操作.
Interruption is voluntary and requires the cooperation of the interrupted thread. The thread can’t act on the interrupt flag status until it is running, because some code has to check the flag and act on it.
更多推荐
线程可以被中断之前是否需要处于RUNNABLE状态?
发布评论