Loading

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;
            }
        }
    }
}
posted @ 2022-02-16 00:12  Cn_FallTime  阅读(45)  评论(0编辑  收藏  举报