java 线程 停止,休眠,礼让,强制执行,观测线程状态,优先级,守护进程

本文探讨了Java中线程的停止机制,避免使用`stop()`和`destroy()`,推荐使用标志控制。还介绍了如何通过休眠实现延时,模拟倒计时和打印系统时间。进程礼让与状态观察也进行了深入讲解,以及如何设置和理解进程优先级。最后,讨论了守护进程的概念和Java中的线程调度原理。
摘要由CSDN通过智能技术生成

线程程停止stop

  1. 不建议使用jdk自带的工具stop(), destroy() etc.
  2. 使用flag,当flag为true,线程工作,相反,则停止.
public class TestStop implements Runnable{
    private boolean flag = true;
    @Override
    public void run() {
        int i = 0; //显示进程运行的次数....
        while (flag){
            System.out.println("Thread is running ......" + i++);
        }
    }
    public void stop(){
        flag = false;
    }

    public static void main(String[] args) {
        TestStop testStop = new TestStop();
        new Thread(testStop).start();
        for (int i = 0; i < 1000; i++) {
            System.out.println("main" + i);
            if(i == 900){
                testStop.stop();
                System.out.println("stop!!!");
            }
        }
    }
}

在main中的i达到900前,testStop与main并行,直到main达到900, testStop被终止。

线程休眠sleep

  1. 使用休眠可以模拟延时,倒计时,打印系统时间等。

模拟延时

public class TestThread4 implements Runnable{
    private int ticket = 15;
    public void run() {
        while(true){
            if(ticket < 0){
                break;
            }
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "get one ticket" + ticket--);
        }
    }

    public static void main(String[] args) {
        TestThread4 testThread4 = new TestThread4();
        new Thread(testThread4, "小明").start();
        new Thread(testThread4, "黄牛").start();
        new Thread(testThread4, "老师").start();

    }
}

模拟延时可以更加反映出场景的真实情况,延时可以增大事件的发生性。当延迟为1000时,在本机的结果如下。在这里插入图片描述
显然出现两个人抢到同一张票以及抢到负数票是不应该被允许的。

模拟倒计时

public class CountDown implements Runnable{
    @Override
    public void run() {
        int counter = 10;
        while (counter > 0){
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(counter--);
        }
    }

    public static void main(String[] args) {
        CountDown countDown = new CountDown();
        new Thread(countDown).start();
    }
}

打印系统时间

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

public class PrintTime {
    public static void main(String[] args) {
        Date time = new Date(System.currentTimeMillis());
        while(true){
            try {
                Thread.sleep(1000);
                System.out.println(new SimpleDateFormat("HH:mm:ss").format(time));
                time = new Date(System.currentTimeMillis());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

#进程礼让yield

  1. 礼让不一定成功,礼让是指进入cpu的进程与其他cpu回到同一起跑线
    等待cpu调度,cpu可能重复执行进行礼让的进程。
public class TestYield implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + " start to running");
        Thread.yield();
        System.out.println(Thread.currentThread().getName() + " is terminated");
    }

    public static void main(String[] args) {
        TestYield  testYield = new TestYield();
        new Thread(testYield, "a").start();
        new Thread(testYield, "b").start();
    }
}

在这里插入图片描述
礼让失败的例子(上图)
在这里插入图片描述
礼让成功的例子(上图)

观测进程状态

  1. Thread.State 为一个变量类型。
public class CheckState {
    public static void main(String[] args) {
        //lambda表达式 进程休眠5s 
        Thread thread = new Thread(()->{
            for (int i = 0; i < 5; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("================================");
        });

        Thread.State state = thread.getState();
        System.out.println(state);//NEW		

        thread.start();
        state = thread.getState();
        System.out.println(state);//RUNNABLE

        while(state != Thread.State.TERMINATED){
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            state = thread.getState();
            System.out.println(state);//WAITTING 最后一次输出TERMINATED
        }
    }
}

#进程的优先级

  1. Thread.getPriority() 获取当前进程的优先级
  2. Thread.setPriority()设置进程优先级 优先级最大为10 Thread.MAX_PRIORITY.
  3. 设置高的优先级并不总是被CPU优先调度
public class TestPriority implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "--->" + Thread.currentThread().getPriority());
    }

    public static void main(String[] args) {
        System.out.println(Thread.currentThread().getName() + "--->" + Thread.currentThread().getPriority());

        TestPriority testPriority = new TestPriority();

        Thread t1 = new Thread(testPriority);
        Thread t2 = new Thread(testPriority);
        Thread t3 = new Thread(testPriority);
        Thread t4 = new Thread(testPriority);

        t1.start();

        t2.setPriority(3);
        t2.start();

        t3.setPriority(Thread.MAX_PRIORITY);
        t3.start();

        t4.setPriority(8);
        t4.start();

    }
}

在这里插入图片描述
执行结果(上图)

守护进程

  1. Thread.setDaemon(true)将一个进程设置为守护进程
  2. JVM需要等待用户进程都执行完毕才退出
  3. JVM并不需要等待守护进程的TERMINATED
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值