Java 学习笔记之 线程sleep方法

mac2022-06-30  55

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

运行结果:

 

转载于:https://www.cnblogs.com/AK47Sonic/p/7666011.html

最新回复(0)