Java基础学习:多线程12(线程休眠:sleep )
-
线程休眠:sleep
-
sleep(时间)指定当前线程阻塞的毫秒数;
-
sleep存在异常InterruptedException;
-
-
sleep可以模拟网络延时,倒计时等;
-
每个对象都有一个锁,sleep不会释放锁;
-
-
代码案例:模拟网络延时:作用:放大问题的发生性
/**
* 模拟网络延时:放大问题的发生性;
*
* 多个线程共享一个对象;不安全
*/
public class TestSleep implements Runnable {
//票数
private int ticketNums=10;
//重写run()方法:
-
代码案例2:模拟倒计时:
/**
* 1,模拟倒计时:
* 2,打印当前时间:
*
*
*/
public class TestSleep2 {
public static void main(String[] args) {
//打印当前系统时间
Date startTime=new Date(System.currentTimeMillis());
while (true){
try {
Thread.sleep(1000);
//打印时间
System.out.println(new SimpleDateFormat("yyyy-MM-dd :HH:mm:ss").format(startTime));
//更新时间
startTime=new Date(System.currentTimeMillis());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//模拟倒计时
public static void tenDown() throws InterruptedException{
int num=10;
while (true){
Thread.sleep(1000);
System.out.println(num--);
if(num<=0){
break;//退出循环
}
}
}
}

浙公网安备 33010602011771号