Run和Start的区别,线程的生命周期,优先级,礼让和守护线程

线程常用方法和线程的状态

线程的生命周期图,及其调用线程的方法会改变的状态

 

 

调用run和start()的区别

复制代码
package org.dance.day1;

import org.dance.tools.SleepTools;

/**
 * 线程调用 run 和 start 方法的区别
 * @author ZYGisComputer
 */
public class StartAndRun {

    /**
     * 继承Thread类
     */
    private static class ThreadRun extends Thread{
        @Override
        public void run() {
            int i = 90;
            while (i>0){
                SleepTools.ms(1000);
                System.out.println("I am "+Thread.currentThread().getName()+" and now the i = "+ i);
                i--;
            }
        }
    }

    public static void main(String[] args) {

        // 执行run
//        executeRun();
        // 执行start
        executeStart();

    }

    public static void executeRun(){
        ThreadRun thread = new ThreadRun();
        thread.setName("run");
        // 调用线程的Run方法
        thread.run();
        // 执行结果
        // I am main and now the i = 90
    }

    public static void executeStart(){
        ThreadRun thread = new ThreadRun();
        thread.setName("run");
        // 调用线程的Run方法
        thread.start();
        // 执行结果
        // I am run and now the i = 90
    }

}
复制代码

SleepTools.java 这个只是一个小工具类,用于线程休眠的

复制代码
package org.dance.tools;

import java.util.concurrent.TimeUnit;

/**
 * 类说明:线程休眠辅助工具类
 */
public class SleepTools {

    /**
     * 按秒休眠
     * @param seconds 秒数
     */
    public static final void second(int seconds) {
        try {
            TimeUnit.SECONDS.sleep(seconds);
        } catch (InterruptedException e) {
        }
    }

    /**
     * 按毫秒数休眠
     * @param seconds 毫秒数
     */
    public static final void ms(int seconds) {
        try {
            TimeUnit.MILLISECONDS.sleep(seconds);
        } catch (InterruptedException e) {
        }
    }
}
复制代码

线程的优先级:

  取值为1~10,缺省为5,但是线程的优先级并不可靠,不建议作为线程开发时候的手段,因为有的操作系统可能会忽略线程的执行优先级,所以开发中需要将这个不确定因素列如其中

设置线程的优先级方法,在源码中可以看见最小是1 默认是5 最大是10  大于或者小于报错

复制代码
/**
     * The minimum priority that a thread can have.
     */
    public final static int MIN_PRIORITY = 1;

   /**
     * The default priority that is assigned to a thread.
     */
    public final static int NORM_PRIORITY = 5;

    /**
     * The maximum priority that a thread can have.
     */
    public final static int MAX_PRIORITY = 10;

public final void setPriority(int newPriority) {
        ThreadGroup g;
        checkAccess();
      
if (newPriority > MAX_PRIORITY || newPriority < MIN_PRIORITY) { throw new IllegalArgumentException(); } if((g = getThreadGroup()) != null) { if (newPriority > g.getMaxPriority()) { newPriority = g.getMaxPriority(); } setPriority0(priority = newPriority); } }
复制代码

守护线程:

  和主线程共死,finally不能保证一定会执行

复制代码
package org.dance.day1;

import org.dance.tools.SleepTools;

/**
 * 守护线程
 * @author ZYGisComputer
 */
public class DaemonThread {

    /**
     * 继承Thread类
     */
    private static class UseThread extends Thread {

        public UseThread(String threadName) {
            super(threadName);
        }

        @Override
        public void run() {
            try {
                String name = Thread.currentThread().getName();
                while (!isInterrupted()) {
                    System.out.println("当前线程:" + name);
                }
                System.out.println(name + " interrupt flag is " + isInterrupted());
            } finally {
                System.out.println("执行 finally");
            }
        }
    }

    public static void main(String[] args) {
        // 执行不是守护线程
//        noDaemon();
        // 执行守护线程
        daemon();
        // 对比之下就可以看到
        // 不是守护线程 需要中断 主线程执行完毕之后不会停止 finally语句块一定会执行
        // 守护线程 主线程执行完毕立即停止 finally语句块不一定会执行
    }

    public static void noDaemon(){
        UseThread useThread = new UseThread("DaemonThread");
        useThread.start();
        SleepTools.ms(5);
        useThread.interrupt();
    }

    public static void daemon(){
        UseThread useThread = new UseThread("DaemonThread");
        useThread.setDaemon(true);
        useThread.start();
        SleepTools.ms(5);
    }

}
复制代码

yield()方法

  让出CPU的执行权,将线程的状态从运行转到可运行状态,但是下个时间片,该线程依然有可能被再次选中执行

作者:彼岸舞

时间:2020\09\15

内容关于:并发编程

本文来源于网络,只做技术分享,一概不负任何责任

posted @   彼岸舞  阅读(260)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 上周热点回顾(3.3-3.9)
· AI 智能体引爆开源社区「GitHub 热点速览」
点击右上角即可分享
微信分享提示