线程休眠

模拟网络延时

放大问题的发生性

//模拟网络延时:放大问题的发生性
public class TestSleep implements Runnable{
//票数
private int ticketNums = 10;
@Override
public void run() {
while (true){
if(ticketNums<=0){
break;
}
//模拟延时
try {
Thread.sleep(200); // 毫秒
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"拿到了第"+ticketNums--+"张票");
}
}
public static void main(String[] args) {
TestSleep ticket = new TestSleep();
new Thread(ticket,"小明").start();
new Thread(ticket,"小红").start();
new Thread(ticket,"小华").start();
}
}

模拟倒计时

//模拟倒计时
public class TestSleep2{
public static void main(String[] args) {
try {
tenDown();
} 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;
}
}
}
}

打印系统当前时间

public static void main(String[] args) {
//打印当前系统时间
Date date = new Date(System.currentTimeMillis()); //获取系统当前时间
while (true){
try {
Thread.sleep(1000);
String format = new SimpleDateFormat("HH-mm-ss").format(date);
System.out.println(format);
// 更新系统当前时间
date = new Date(System.currentTimeMillis());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
posted @   流浪猫老大  阅读(8)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示