ps网站背景图片怎么做,中国电子商务平台有哪些,免费在线图片制作,番禺区核酸检测点文章目录 前言一、run() 和 start() 方法二、sleep() 方法三、join() 方法总结 前言
提示#xff1a;若对Thread没有基本的了解#xff0c;可以先阅读以下文章#xff0c;同时部分的方法已经在如下两篇文章中介绍过了#xff0c;本文不再重复介绍#xff01;#xff01;… 文章目录 前言一、run() 和 start() 方法二、sleep() 方法三、join() 方法总结 前言
提示若对Thread没有基本的了解可以先阅读以下文章同时部分的方法已经在如下两篇文章中介绍过了本文不再重复介绍 【Java中Tread和Runnable创建新的线程的使用方法】 【Java中的Thread线程的七种属性的使用和分析】 提示以下是本篇文章正文内容下面案例可供参考
一、run() 和 start() 方法 代码示例 1
public class Ceshi {public static void main(String[] args) {Thread t new Thread(new Runnable() {Overridepublic void run() {System.out.println(hello world);}});t.run();System.out.println(t.isAlive());System.out.println(t.getState());}
}输出结果 代码示例 2
public class Ceshi {public static void main(String[] args) {Thread t new Thread(new Runnable() {Overridepublic void run() {System.out.println(hello world);}});t.start();System.out.println(t.isAlive());System.out.println(t.getState());}
}输出结果 由此看出 t.run()这条语句能够调用run()方法但是没有启动线程线程仍然处于NEW的状态并没有启动线程只是调用了一次run()方法。 t.start()这条语句同样能够调用run()方法但是它真正的启动了t线程线程处于RUNNABLE的状态然后t线程调用了run()方法 二、sleep() 方法 代码示例
public class Ceshi {public static void main(String[] args) throws InterruptedException {Thread t1 new Thread(() - {System.out.println(工作中);});t1.start();//该方法为静态方法直接使用类名调用Thread.sleep(3000);//main线程休眠3秒后才能继续执行下面的语句System.out.println();System.out.println(耗时三秒工作完成);}
}输出结果 结论 该方法写在那个线程里就会使哪个线程休眠规定的时间其他的线程不受影响。public static void sleep(long millis, int nanos)休眠millis毫秒后再休眠nanos纳秒范围0-999999纳秒因为线程的调度是不可控的所以这个方法只能保证实际休眠时间是大于等于参数设置的休眠时间的。 三、join() 方法 代码示例
public class Ceshi {public static void main(String[] args) throws InterruptedException {Thread t1 new Thread(() - {System.out.println(工作一需要3秒);try {Thread.sleep(4000);} catch (InterruptedException e) {throw new RuntimeException(e);}});Thread t2 new Thread(() - {System.out.println(工作一已完成开始工作二);try {Thread.sleep(3000);} catch (InterruptedException e) {throw new RuntimeException(e);}});Thread t3 new Thread(() - {System.out.println(工作二已完成开始工作三);try {Thread.sleep(2000);} catch (InterruptedException e) {throw new RuntimeException(e);}});Thread t4 new Thread(() - {System.out.println(工作三已完成开始工作四);try {Thread.sleep(1000);} catch (InterruptedException e) {throw new RuntimeException(e);}});//在main线程中调用t.join()就是让main线程等待t线程执行结束保证t先结束t1.start();t1.join();//t1的任务不结束不会执行下面的语句t2.start();t2.join();//t2不结束不继续进行t3.start();t3.join();//同理t4.start();t4.join();//同理}
}输出结果 结论 有时我们需要等待一个线程完成它的工作后才能进行自己的下一步工作。该方法能够保证线程的任务有序执行不会发生抢占式的进行。同时还有带参数的重载方法public void join(long millis) 等待线程结束最多等millis毫秒,public void join(long millis, int nanos)在millis毫秒的基础上再加上nanos纳秒范围0-999999纳秒 总结
除了以上常用的方法还有许多的方法在前言中的文章已经详细介绍和使用如若该文中没有找到你需要的请跳转到前言的链接