p12 线程休眠
模拟网络延时:放大问题的发生性
Thread.sleep()
package kuang.com.demo;
//模拟网络延时:放大问题的发生性
//问题:多个线程操作同一个资源的情况下,线程不安全,数据紊乱
public class Testsleep implements Runnable{
private int tickNums =10;
@Override
public void run() {
while(true){
if(tickNums<=0){
break;
}
//模拟延时
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"-->拿到第"+tickNums--+"张票");
}
}
public static void main(String[] args) {
Testsleep ticket = new Testsleep();
new Thread(ticket,"泰罗").start();
new Thread(ticket,"雷欧").start();
new Thread(ticket,"阿斯特拉").start();
}
}
模拟倒计时和获取系统当前时间
package kuang.com.demo;
import java.text.SimpleDateFormat;
import java.util.Date;
//模拟倒计时
public class TestStop2 {
public static void main(String[] args) {
/*try {
tenDown();
} catch (InterruptedException e) {
e.printStackTrace();
}*/
Date startTime = new Date(System.currentTimeMillis());//获取系统当前时间
while (true){
try {
Thread.sleep(1000);
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;
}
}
}
}