zoukankan      html  css  js  c++  java
  • 1.5 sleep()方法

    方法sleep()的作用是在指定的毫秒数内让当前"正在执行的线程"休眠(暂停执行)。这个“正在执行的线程”是指this.currentThread()返回的线程。

    注:this.currentThread()在IDE中报错,提示使用类名调用静态方法,但实际并不影响运行。

    线程代码:

    public class Thread1 extends Thread {
        @Override
        public void run() {
            try {
                System.out.println("run threadName = " + this.currentThread().getName() + " begin");
                Thread.sleep(2000);
                System.out.println("run threadName = " + this.currentThread().getName() + " end");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    执行代码:

    public class Main {
        public static void main(String[] args) {
            Thread1 t1 = new Thread1();
            System.out.println("begin = " + System.currentTimeMillis());
            t1.run();
            System.out.println("end = " + System.currentTimeMillis());
        }
    }

    执行结果:

    创建线程代码2:

    public class Thread2 extends Thread {
        @Override
        public void run() {
            try {
                System.out.println("run threadName = " + this.currentThread().getName() + " begin =" +System.currentTimeMillis());
                Thread.sleep(2000);
                System.out.println("run threadName = " + this.currentThread().getName() + " end =" +System.currentTimeMillis());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    创建执行代码:

    public class Main {
        public static void main(String[] args) {
            Thread2 t2 = new Thread2();
            System.out.println("begin = " + System.currentTimeMillis());
            t2.start();
            System.out.println("end = " + System.currentTimeMillis());
        }
    }

    执行结果:

    注:main与Thread2线程是异步执行的,所以先打印出begin与end,然后再打印run begin与run end

    源码地址:https://github.com/lilinzhiyu/threadLearning

     

    本文内容是书中内容兼具自己的个人看法所成。可能在个人看法上会有诸多问题(毕竟知识量有限,导致认知也有限),如果读者觉得有问题请大胆提出,我们可以相互交流、相互学习,欢迎你们的到来,心成意足,等待您的评价。

  • 相关阅读:
    趁热讲讲skin.xml支持的标签和attributes
    如何配置和编译ogre 1.7.0 + cegui 0.7.1
    关于OGRE基础教程6中CEGUI的layout文件can not locate的问题
    skin.xml皮肤配置讲解
    OCX控件注册相关(检查是否注册,注册,反注册)
    重回博客园继续我的 GUI库
    窗口类的定义
    UI库需要完成的任务
    屏幕截图代码
    深入C++的默认构造函数1
  • 原文地址:https://www.cnblogs.com/lilinzhiyu/p/7941559.html
Copyright © 2011-2022 走看看