• [JavaEE]如何唤醒Sleep中的线程


    主线程调用子线程的interrupt()方法,导致子线程抛出InterruptedException, 在子线程中catch这个Exception,不做任何事即可从Sleep状态唤醒线程,继续执行。 如下测试。

    public class SleepThreadTest {

        public static void main(String[] args){
            Thread myThread = new Thread(new TestThread(1));
            myThread.start();
            try {
                Thread.sleep(3000);
                myThread.interrupt();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            
            
            
        }
        
        private static class TestThread implements Runnable{
            private int i;
            public TestThread(int i){
                this.i = i;
            }

            @Override
            public void run() {
                while(i<10){
                    System.out.println(i + "   time:" + new Date());
                    i++;
                    if(i==4){
                        try {
                            Thread.sleep(10000);
                        } catch (InterruptedException e1) {
                            System.out.println("interrupt myThread...");
                        }

                    }
                }
            }
            
        }
    }

    result:

    1   time:Mon Jun 16 15:19:56 CST 2014
    2   time:Mon Jun 16 15:19:56 CST 2014
    3   time:Mon Jun 16 15:19:56 CST 2014
    interrupt myThread...
    4   time:Mon Jun 16 15:19:59 CST 2014
    5   time:Mon Jun 16 15:19:59 CST 2014
    6   time:Mon Jun 16 15:19:59 CST 2014
    7   time:Mon Jun 16 15:19:59 CST 2014
    8   time:Mon Jun 16 15:19:59 CST 2014
    9   time:Mon Jun 16 15:19:59 CST 2014

  • 相关阅读:
    Java的HashMap
    为什么 char c = 'A';c += 32; 结果输出的是 'a'?
    java中整数的常量优化机制
    IDEA2019版中文汉化包
    asp.net项目协作开发时,常常要忽略版本控制的目录
    SQLServer同步数据到ElasticSearch
    为什么不建议在微信小程序的TarBar上检查统一登录后跳转页面
    nginx的热备方式
    HTTP 和FTP 状态信息总结(留着自己用)
    Web Api 简介
  • 原文地址:https://www.cnblogs.com/spec-dog/p/3791043.html
Copyright © 2020-2023  润新知