• 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());
        }
    }

    运行结果:

  • 相关阅读:
    51串口通信
    juicer使用备忘
    51单片机音乐盒程序
    最精简24L01程序--接收
    sqlserver 数据库迁移
    sqlserver自增主键
    js keycode
    tabindex 去掉虚线
    div 绑定keyup
    sqlserver 当前时间减去30天
  • 原文地址:https://www.cnblogs.com/AK47Sonic/p/7666011.html
Copyright © 2020-2023  润新知