|NO.Z.00097|——————————|BigDataEnd|——|Java&多线程.V09|——|Java.v09|sleep方法使用|

一、sleep方法的使用:常用的方法(重点)
方法声明 功能介绍
static void yield() 当前线程让出处理器(离开Running状态),
使当前线程进入Runnable状态等待
static void sleep(times) 使当前线程从 Running 放弃处理器进入Block状态, 休眠times毫秒,
再返回到Runnable如果其他线程打断当前线程的Block(sleep),
就会发生InterruptedException。
int getPriority() 获取线程的优先级
void setPriority(int newPriority) 修改线程的优先级。优先级越高的线程不一定先执行,
但该线程获取到时间片的机会会更多一些
void join() 等待该线程终止
void join(long millis) 等待参数指定的毫秒数
boolean isDaemon()  用于判断是否为守护线程
voidsetDaemon(booleanon) 用于设置线程为守护线程
二、编程代码
package com.yanqi.task18;

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

public class ThreadSleepTest extends Thread {
    // 声明一个布尔类型的变量作为循环是否执行的条件
    private boolean flag = true;

    // 子类中重写的方法不能抛出更大的异常
    @Override
    public void run() {
        // 每隔一秒获取一次系统时间并打印,模拟时钟的效果
        while (flag) {
            // 获取当前系统时间并调整格式打印
//            LocalDateTime.now();
            Date d1 = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            System.out.println(sdf.format(d1));

            // 睡眠1秒钟
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {

        ThreadSleepTest tst = new ThreadSleepTest();
        tst.start();

        // 主线程等待5秒后结束子线程
        System.out.println("主线程开始等待...");
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 停止子线程  过时  不建议使用
        //tst.stop();
        tst.flag = false;
        System.out.println("主线程等待结束!");
    }
}
三、编译打印
D:\JAVA\jdk-11.0.2\bin\java.exe "-javaagent:D:\IntelliJIDEA\IntelliJ IDEA 2019.3.3\lib\idea_rt.jar=50632:D:\IntelliJIDEA\IntelliJ IDEA 2019.3.3\bin" -Dfile.encoding=UTF-8 -classpath E:\NO.Z.10000——javaproject\NO.H.00001.javase\javase\out\production\javase com.yanqi.task18.ThreadSleepTest
主线程开始等待...
2021-08-01 20:12:13
2021-08-01 20:12:14
2021-08-01 20:12:15
2021-08-01 20:12:16
2021-08-01 20:12:17
主线程等待结束!

Process finished with exit code 0

 
 
 
 
 
 
 
 
 

Walter Savage Landor:strove with none,for none was worth my strife.Nature I loved and, next to Nature, Art:I warm'd both hands before the fire of life.It sinks, and I am ready to depart
                                                                                                                                                   ——W.S.Landor

 

posted on 2022-04-04 15:44  yanqi_vip  阅读(13)  评论(0)    收藏  举报

导航