Java线程状态sleep

本文详细探讨了Java线程中的sleep状态,解释了如何使用Thread.sleep()方法让线程暂停执行,并讨论了它与其他线程状态的区别,以及在多线程编程中如何合理利用sleep来控制线程调度。
摘要由CSDN通过智能技术生成

package thread.state;

import thread.demo01.TestThread4;

public class TestSleep implements Runnable{

    int tickerNums=10;

    @Override
    public void run() {
        while (true) {
            if(tickerNums<=0){
                break;
            }

            try{
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"--->>Get ticker id : "+tickerNums--);
        }
    }

    public static void main(String[] args) {
        TestSleep ticket = new TestSleep();

        new Thread(ticket,"学生").start();
        new Thread(ticket,"老师").start();
        new Thread(ticket,"黄牛").start();
    }
}


package thread.state;

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

public class TestSleep2 {
    public static void main(String[] args) {
//        10
//        9
//        8
//        7
//        6
//        5
//        4
//        3
//        2
//        1
//        0
        try{
            tenDown();
        } catch (Exception e) {
            e.printStackTrace();
        }

//        20:01:35
//        20:01:36
//        20:01:37
//        20:01:38
//        20:01:39
//        20:01:40
//        20:01:41
//        20:01:42
//        20:01:43
        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;
            }
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值