前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Run和Start的区别,线程的生命周期,优先级,礼让和守护线程

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

作者头像
彼岸舞
发布2020-09-30 11:54:10
3340
发布2020-09-30 11:54:10
举报

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

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

调用run和start()的区别

代码语言:javascript
复制
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 这个只是一个小工具类,用于线程休眠的

代码语言:javascript
复制
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  大于或者小于报错

代码语言:javascript
复制
/**
     * 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不能保证一定会执行

代码语言:javascript
复制
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

内容关于:并发编程

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

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-09-15 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档