线程的sleep()方法的简单使用

线程的sleep方法签名位: 

public static void sleep(long millis) throws InterruptException,  是静态方法,使目前正在执行的线程休眠millis毫秒

package com.demo;
class MyThread implements Runnable{
	public void run(){	
		for(int i = 0; i < 4; i++){
			try {
				System.out.println(Thread.currentThread().getName()+ "休眠0.5秒!");
				Thread.sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("当前运行的线程名称: "+ Thread.currentThread().getName());	
		}
			
	}
}
public class demo   {
	public static void main(String[] args){
		MyThread mt1 = new MyThread();
	    Thread th = new Thread(mt1, "线程A");
	    System.out.println("\n Thread is starting");
	    th.start();
	    try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			
			e.printStackTrace();
		}
        System.out.println("\n主线程已经休眠2s "+ Thread.currentThread().getName());	
	}

}

运行结果如下:

 Thread is starting
线程A休眠0.5秒!
当前运行的线程名称: 线程A
线程A休眠0.5秒!
当前运行的线程名称: 线程A


主线程已经休眠1s main
线程A休眠0.5秒!
当前运行的线程名称: 线程A
线程A休眠0.5秒!
当前运行的线程名称: 线程A


从运行结果可以分析,当线程A休眠1s后,主线程即也已经休眠1s,当前运行的线程为主线程main,接下来线程A继续运行。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值