老师您好,您在本节5分15秒说,“要把子线程的休眠时间加长,改为Thread.sleep(2000),要确保在子线程休眠过程中,去中断子线程”。(ps:这块语速有点快,可能复述不清楚,以视频为准)。
我的疑问是:
第一个疑问:在5-4节时候,讲的是“interrupt是一个信号,这个信号并不是实时检测的,也不是每行代码都能检测的,只有程序运行到sleep时,才能检测到线程被中断了,然后会抛出异常”。 感觉这2个说法不一样,望老师指导。
第二疑问:我自己试了子线程的休眠时间,改为比1s小,例如Thread.sleep(50),其达到的效果和Thread.sleep(2000)是一样的。 所以还是不理解为啥要设置Thread.sleep(2000)啊?
Thread.sleep(50)的代码:
public class RigthWayStopThreadInProd implements Runnable{ @Override public void run(){ while (true){ System.out.println("go"); throwInMethod(); } } private void throwInMethod(){ try { Thread.sleep(50); }catch (InterruptedException e){ e.printStackTrace(); } } public static void main(String[] args) throws InterruptedException{ Thread thread = new Thread(new RigthWayStopThreadInProd()); thread.start(); Thread.sleep(1000); thread.interrupt(); } }
Thread.sleep(50)的结果:
"D:\Program Files\Java\jdk1.8.0_25\bin\java.exe" -Dvisualvm.id=206304728283300 "-javaagent:D:\Program Files\JetBrains\IntelliJ IDEA 2018.2.6\lib\idea_rt.jar=8549:D:\Program Files\JetBrains\IntelliJ IDEA 2018.2.6\bin" -Dfile.encoding=UTF-8 -classpath "D:\Program Files\Java\jdk1.8.0_25\jre\lib\charsets.jar;D:\Program Files\Java\jdk1.8.0_25\jre\lib\deploy.jar;D:\Program Files\Java\jdk1.8.0_25\jre\lib\ext\access-bridge-64.jar;D:\Program Files\Java\jdk1.8.0_25\jre\lib\ext\cldrdata.jar;D:\Program Files\Java\jdk1.8.0_25\jre\lib\ext\dnsns.jar;D:\Program Files\Java\jdk1.8.0_25\jre\lib\ext\jaccess.jar;D:\Program Files\Java\jdk1.8.0_25\jre\lib\ext\jfxrt.jar;D:\Program Files\Java\jdk1.8.0_25\jre\lib\ext\localedata.jar;D:\Program Files\Java\jdk1.8.0_25\jre\lib\ext\nashorn.jar;D:\Program Files\Java\jdk1.8.0_25\jre\lib\ext\sunec.jar;D:\Program Files\Java\jdk1.8.0_25\jre\lib\ext\sunjce_provider.jar;D:\Program Files\Java\jdk1.8.0_25\jre\lib\ext\sunmscapi.jar;D:\Program Files\Java\jdk1.8.0_25\jre\lib\ext\sunpkcs11.jar;D:\Program Files\Java\jdk1.8.0_25\jre\lib\ext\zipfs.jar;D:\Program Files\Java\jdk1.8.0_25\jre\lib\javaws.jar;D:\Program Files\Java\jdk1.8.0_25\jre\lib\jce.jar;D:\Program Files\Java\jdk1.8.0_25\jre\lib\jfr.jar;D:\Program Files\Java\jdk1.8.0_25\jre\lib\jfxswt.jar;D:\Program Files\Java\jdk1.8.0_25\jre\lib\jsse.jar;D:\Program Files\Java\jdk1.8.0_25\jre\lib\management-agent.jar;D:\Program Files\Java\jdk1.8.0_25\jre\lib\plugin.jar;D:\Program Files\Java\jdk1.8.0_25\jre\lib\resources.jar;D:\Program Files\Java\jdk1.8.0_25\jre\lib\rt.jar;E:\.IntelliJIdea2018.2\concurrency_in_practice\target\classes" threadcorekonwledge.stopthreads.RigthWayStopThreadInProd go go go go go go go go go go go go java.lang.InterruptedException: sleep interrupted at java.lang.Thread.sleep(Native Method) at threadcorekonwledge.stopthreads.RigthWayStopThreadInProd.throwInMethod(RigthWayStopThreadInProd.java:20) at threadcorekonwledge.stopthreads.RigthWayStopThreadInProd.run(RigthWayStopThreadInProd.java:14) at java.lang.Thread.run(Thread.java:745) go go go go go go go go go go go go Process finished with exit code -1