Java多线程10-线程休眠
10、线程休眠_sleep
- sleep(long millis) 指定当前线程阻塞的毫秒数
- sleep存在异常InterruptException
- sleep时间达到后线程进入就绪状态
- sleep可以模拟网络延时,倒计时等
- 每一个对象都有一个锁,sleep不会释放锁
抢票Demo#
//模拟网络时延可以放大问题的发生性
public class TestSleep implements Runnable{
//票数
private int tickerNums =10;
@Override
public void run() {
while (true){
if (tickerNums <=0) {
break;
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"拿到了第"+tickerNums+"票");//Thread.currentThread().getName()可以获得当前执行线程的名字
tickerNums--;
}
}
public static void main(String[] args) {
TestSleep testSleep=new TestSleep();
new Thread(testSleep,"小明").start();
new Thread(testSleep,"老司机").start();
new Thread(testSleep,"黄牛").start();
//输出后发现问题:多个线程操作同一个资源的情况下,线程不安全,数据紊乱
}
}
模拟倒计时+打印当前系统时间Demo#
//模拟倒计时
public class TestSleep2 {
public static void main(String[] args) {
//d倒计时模拟器调用
// try {
// tenDown();
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
//打印系统当前时间
Date starttime=new Date(System.currentTimeMillis());
while (true){
try {
Thread.sleep(1000);//这样操作有个问题,打印出的时间永远比系统时间慢1秒
System.out.println(new SimpleDateFormat("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;
}
}
}
}
作者:Cn_FallTime
出处:https://www.cnblogs.com/CnFallTime/p/15898704.html
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义