zoukankan      html  css  js  c++  java
  • Java 学习笔记之 线程sleep方法

    线程sleep方法:

    单主线程使用sleep:

    Main线程差了2000毫秒。

    public class MainSleepThread extends Thread{
        @Override
        public void run() {
    
            try {
                System.out.println(this.currentThread().getName() + " begin");
                Thread.sleep(2000);
                System.out.println(this.currentThread().getName() + " end");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    
        }
    }
    
    public class ThreadRunMain {
        public static void main(String[] args) {
    
            testMainSleepThread();
    
        }
    
        public static void testMainSleepThread(){
            MainSleepThread mst = new MainSleepThread();
            System.out.println("begin = " + System.currentTimeMillis());
            mst.run();
            System.out.println("end = " + System.currentTimeMillis());
        }
    }

    运行结果:

    非Main线程使用sleep:

    Main线开始和结束时间一样,而非主线程差了2000毫秒。

    public class ThreadSleepThread 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 (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    
    public class ThreadRunMain {
        public static void main(String[] args) {
            testThreadSleepThread();
        }
    
        public static void testThreadSleepThread(){
            ThreadSleepThread tst = new ThreadSleepThread();
            System.out.println("begin = " + System.currentTimeMillis());
            tst.start();
            System.out.println("end = " + System.currentTimeMillis());
        }
    }

    运行结果:

  • 相关阅读:
    一文搞懂Raft算法
    设计数据密集型应用第三部分:派生数据
    对一次架构设计的总结和反思
    One take,可望而不可即
    设计数据密集型应用第二部分:分布式系统的机遇与挑战
    [代码重构]简化函数调用
    [代码重构]简化函数调用
    [Vue专题] 对比vue-cli2.x和vue-cli3.x的搭建
    npm ERR! code ENOLOCAL
    Jenkins配置基于角色的项目权限管理
  • 原文地址:https://www.cnblogs.com/AK47Sonic/p/7666011.html
Copyright © 2011-2022 走看看