线程可以被中断之前是否需要处于RUNNABLE状态?

编程入门 行业动态 更新时间:2024-10-23 15:29:56
本文介绍了线程可以被中断之前是否需要处于RUNNABLE状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在被中断方法中断之前,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状态?

本文发布于:2023-11-05 04:59:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1559970.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:线程   状态   RUNNABLE

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!