日志文章

2019-12-25 aflfte2011

线程阻塞(sleep的使用)

package com.aflfte.state;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 线程阻塞
 * sleep的应用
 * 1.用于模拟网络的延时操作,放大了发生问题的可能性
 * 2.模拟休息
 * 3.模拟倒计时
 * @author root
 *
 */
public class BlockedSleep{
    public static void main(String[] args) throws Exception {
        Date endtime=new Date(System.currentTimeMillis()+1000*10);
        long end=endtime.getTime();
        while(true) {
            System.out.println(new SimpleDateFormat("mm:ss").format(endtime));
            Thread.sleep(1000);
            endtime=new Date(endtime.getTime()-1000);
            if(end-10000>endtime.getTime()) {
                break;
            }
        }
    }
    public static void test() throws Exception {
        //倒数10个数
        int num=10;
        while(num!=0) {
            Thread.sleep(1000);
            System.out.println(num--);
        }
    }
    public static void websleep() {
        Web12306 web=new Web12306();
        new Thread(web,"张三").start();
        new Thread(web,"李四").start();
        new Thread(web,"王五").start();
    }
}

class Web12306 implements Runnable{
    private int piao=99;
    @Override
    public void run() {
        while(true) {
            if(piao<0) {
                break;
            }
            //模拟网络延时200ms
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                // TODO 自动生成的 catch 块
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"-->"+piao--);
        }
    }
    
}

« Yield线程礼让 | 线程的终止操作方法»