public static void sleep(Long millis):使当前正在执行的线程以指定的毫秒数暂停(暂时停止执行)。毫秒数结束之后,线程继卖执行
sleep(简称线程休眠)
举例:
举例:
public static void main(String[] args) throws IOException { do { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS"); Date date = new Date(); System.out.println(simpleDateFormat.format(date)); Thread.sleep(1000); }while(true); }
举例:
public static void main(String[] args) { Thread thread = new Thread(() -> { String threadName = Thread.currentThread().getName(); System.out.println(threadName + "线程开始执行"); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(threadName + "任务执行完毕"); }, "work"); thread.start(); System.out.println("main线程执行"); }
举例:
public static void main(String[] args) { Thread t1 = new Thread(new myThread(), "thread1"); Thread t2 = new Thread(new myThread(), "thread2"); t1.start(); t2.start(); } } class myThread implements Runnable{ public void run() { System.out.println(Thread.currentThread().getName()+"开始执行"); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"执行结束"); } }
创建多线程程序的第二种方式_实现Runnable接口
创建多线程的第二种方法:实现Runnable接口
Runnable接口一个由哪写打算通过某一线程执行其实例的类来实现。类必须定义一个称为run的无参数方法
java.lang.Thread类的构造方法
Thread(Runnable target)分配新的Thread对象
Thread(Runnable target,String name)分配新的Thread对象
实现步骤:
1.创建一个Runnable接口的实现类
2.在实现类中重写Runnable接口的run方法,设置线程任务
3.创建一个Runnable接口的实现类对象
4.创建Thread类对象,构造方法中传递Runnable接口的实现类对象
5.调用Thread类中的start方法,开启新的线程执行run方法
举例:
举例:Thread
举例:Runnable
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)