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

     

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

  • 相关阅读:
    弱省胡策 Magic
    CF917D Stranger Trees
    【弱省胡策】Round #5 Count
    【BZOJ2117】 [2010国家集训队]Crash的旅游计划
    「2017 山东一轮集训 Day5」苹果树
    【SDOI2017】天才黑客
    【JXOI2018】守卫
    小程序两种图片加载方式
    小程序之底部栏设计
    小程序之全局变量的设置及使用
  • 原文地址:https://www.cnblogs.com/lilinzhiyu/p/7941559.html
Copyright © 2011-2022 走看看