线程sleep方法的demo详解


 sleep:超时等待指定时间,时间到了之后,重新回到就绪状态,抢到CPU资源后,立马进入运行状态;

package com.roocon.thread.t1;
public class NewThread implements Runnable {

    @Override
    public void run() {
        while(true){
            System.out.println("自定义线程运行了");
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Thread thread = new Thread(new NewThread());//创建线程并且指定线程任务
        thread.start();//启动线程
        while(true){
            System.out.println("主线程运行了");
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

注意:sleep方法要try catch异常,否则不通过。通过加入sleep,可以明显感觉到,每次输出都有一定的时间间隔;

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM