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

运行结果:

Java 学习笔记之 线程sleep方法

 

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

运行结果:

Java 学习笔记之 线程sleep方法

 

相关文章:

  • 2022-12-23
  • 2021-07-06
  • 2021-09-28
  • 2021-08-27
  • 2021-08-03
  • 2021-12-04
  • 2021-04-22
  • 2021-10-31
猜你喜欢
  • 2021-04-03
  • 2021-11-23
  • 2021-10-09
  • 2021-08-11
  • 2021-09-24
  • 2021-08-14
  • 2021-07-28
相关资源
相似解决方案