线程的启动与优先级

119 阅读2分钟

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第18天,点击查看活动详情

start() 和 run() 的区别

start()源码:

public synchronized void start() {
    if (threadStatus != 0)
        throw new IllegalThreadStateException();
    group.add(this);
    boolean started = false;
    try {
        start0();
        started = true;
    } finally {
        try {
            if (!started) {
                group.threadStartFailed(this);
            }
        } catch (Throwable ignore) {
            // 不处理任何异常,如果 start0 抛出异常,则它将被传递到调用堆栈上
        }
    }
}

if (threadStatus != 0) throw new IllegalThreadStateException(); 状态验证,不等于 NEW 则会抛出异常

group.add(this); 通知线程组,此线程即将启动

catch (Throwable ignore) { } 不做任何异常处理,如果抛出异常,则会被传递到调用的方法中

run()源码:

public class Thread implements Runnable {
 
  ......
  
  private Runnable target;
  @Override
  public void run() {
      if (target != null) {
          target.run();
      }
  }
}

run()方法其中是重写的Runnable接口中的run方法。 而start() 方法是属于 Thread 自身的方法,并且使用了synchronized,保证了线程安全。

start() 方法是开启线程的方法,让线程从 NEW 状态转换成 RUNNABLE 状态,而 run() 方法只是一个普通的方法,不会对线程的状态有所影响。

线程的优先级

什么是线程的优先级? 线程优先级被线程调度用来判定何时每个线程允许被优先运行。理论上优先级高的线程比优先级低的线程有几率获得更多的CPU时间。并不是说优先级搞的线程一定先执行。

在java线程Thread类的源代码中,线程优先级的属性有3个:

public final static int MIN_PRIORITY = 1;

public final static int NORM_PRIORITY = 5;

public final static int MAX_PRIORITY = 10

MIN_PRIORITY表示线程可以拥有的最小优先级

NORM_PRIORITY表示线程默认优先级

MAX_PRIORITY表示线程可以拥有的最大优先级

修改线程优先级的方法:setPriority(),源码:

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);
    }
}

if (newPriority > MAX_PRIORITY || newPriority < MIN_PRIORITY) { } 验证优先级的合理性,如果在合理范围之外,则会抛出IllegalArgumentException异常

if (newPriority > g.getMaxPriority()) { newPriority = g.getMaxPriority();} 优先级如果超过线程组的最高优先级,则把优先级设置为线程组的最高优先级,所以线程的优先级有可能并不会和设置的值一样,还要取悦于线程组的优先级。