多线程-五大状态-休眠(sleep)、方法、模拟网络延时、模拟倒计时、每秒打印系统当前时间
概述:
sleep(时间)指定当前线程阻塞的毫秒数
sleep存在异常InterruptedException;
sleep时间达到后线程进入就绪状态
sleep可以模拟网络延时,倒计时等
每一个对象都有一个锁,sleep不释放锁
//模拟网络延时:作用是放到问题的发生性 public class Main implements Runnable{ //票数 private int ticketNums=100; public void run(){ while(true){ if (ticketNums>=0){ //模拟延时 try{ Thread.sleep(200); }catch(InterruptedException e){ e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"拿到了第:"+ticketNums--+"票");//先拿到票再减减 }else{ break; } } } public static void main(String []args){ //创建线程实现类对象 Main t1=new Main(); //创建线程对象,并启三个线程把实现类对象添加到线程,然后为线程命名,注意多个线程操作一个对象是不安全的 Thread ead1=new Thread(t1,"线程1"); Thread ead2=new Thread(t1,"线程2"); Thread ead3=new Thread(t1,"线程3"); //启动线程 ead1.start(); ead2.start(); ead3.start(); } }
//模拟倒计时 public class Main { //倒计时方法 public static void tenDown() throws InterruptedException{ int num=10; while(true){ //让线程这1秒钟跑一次,1000毫秒=1秒 Thread.sleep(1000); System.out.println(num--); if (num<=0){//小于等于0,就结束 break; } } } public static void main (String[] args) { //捕获一下,tenDown自己抛出的异常 try { //调用倒计时方法 tenDown(); } catch(InterruptedException e) { e.printStackTrace(); } } }
//每秒打印系统当前时间 public class Main { //倒计时方法 public static void tenDown() throws InterruptedException{ int num=10; while(true){ //让线程这1秒钟跑一次,1000毫秒=1秒 Thread.sleep(1000); System.out.println(num--); if (num<=0){//小于等于0,就结束 break; } } } public static void main (String[] args) { //打印系统当前时间 Date seartTime=new Date(System.currentTimeMillis());//获取系统当前时间 while(true){ try { Thread.sleep(1000); System.out.println(new SimpleDateFormat("HH:mm:ss").format(seartTime));//"HH:mm:ss":设置获取系统时间的格式 seartTime=new Date(System.currentTimeMillis());//更新当前时间 } catch(Exception e) { } } } }
分类:
java之多线程
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)