package state;
//模拟网络延时的作用:放大问题发生的可能性
public class TestSleep implements Runnable{
private int ticket = 10;
@Override
public void run() {
while (true){
if(ticket<=0){
break;
}
try {
Thread.sleep(100);
} catch (Exception e) {
throw new RuntimeException(e);
}
System.out.println(Thread.currentThread().getName()+"获得了第"+ticket--+"张票");
}
}
public static void main(String[] args) {
TestSleep testSleep = new TestSleep();
new Thread(testSleep ,"小明").start();
new Thread(testSleep ,"小蓝").start();
new Thread(testSleep ,"小红").start();
new Thread(testSleep ,"小三").start();
//System.out.println(testSleep .ticket);
}
}
package state;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TestSleep2 {
public static void main(String[] args) {
// try {
// tenDown();
// } catch (InterruptedException e) {
// throw new RuntimeException(e);
// }
systemTime();
}
//模拟倒计时方法
public static void tenDown() throws InterruptedException {
int num = 10;
while (num>=0){
System.out.println(num--);
Thread.sleep(1000);
}
}
public static void systemTime(){
Date date = new Date(System.currentTimeMillis());//获取系统当前时间
int num = 10;
while (num>=0){
try {
Thread.sleep(100);
System.out.println(new SimpleDateFormat("HH:mm:ss").format(date));
date = new Date(System.currentTimeMillis());//更新时间
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
}
num--;
}
}
}
标签:--,void,System,休眠,num,线程,Date,new,public
From: https://www.cnblogs.com/qt0312/p/17204503.html