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,可以明显感觉到,每次输出都有一定的时间间隔;

线程sleep方法的demo详解

 

相关文章:

  • 2021-10-18
  • 2021-04-18
  • 2022-12-23
  • 2022-12-23
  • 2021-10-05
  • 2021-11-23
  • 2022-12-23
  • 2022-01-09
猜你喜欢
  • 2021-08-06
  • 2021-08-09
  • 2022-01-28
  • 2022-12-23
  • 2022-12-23
  • 2021-10-30
相关资源
相似解决方案