java线程的状态有哪些?

java线程的状态有哪些?如何工作的

线程的状态有哪些

6种状态(源码分析)

    public enum State {
        /**
         * Thread state for a thread which has not yet started.
          初始(NEW):新创建了一个线程对象,但还没有调用start()方法。
         */
        NEW,

        /**
         * Thread state for a runnable thread.  A thread in the runnable
         * state is executing in the Java virtual machine but it may
         * be waiting for other resources from the operating system
         * such as processor.
         Java线程中将就绪(ready)和运行中(running)两种状态笼统的称为“运行”。
线程对象创建后,其他线程(比如main线程)调用了该对象的start()方法。该状态的线程位于可运行线程池中,等待被线程调度选中,获取CPU的使用权,此时处于就绪状态(ready)。就绪状态的线程在获得CPU时间片后变为运行中状态(running)。
         */
        RUNNABLE,

        /**
         * Thread state for a thread blocked waiting for a monitor lock.
         * A thread in the blocked state is waiting for a monitor lock
         * to enter a synchronized block/method or
         * reenter a synchronized block/method after calling
         * {@link Object#wait() Object.wait}.
         表示线程阻塞于锁。
         */
        BLOCKED,

        /**
         * Thread state for a waiting thread.
         * A thread is in the waiting state due to calling one of the following methods:
         * <ul>
         *   <li>{@link Object#wait() Object.wait} with no timeout</li>
         *   <li>{@link #join() Thread.join} with no timeout</li>
         *   <li>{@link LockSupport#park() LockSupport.park}</li>
         * </ul>
         *
         * <p>A thread in the waiting state is waiting for another thread to perform a particular action.
         For example, a thread that has called <tt>Object.wait()</tt>
         * on an object is waiting for another thread to call
         * <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on
         * that object. A thread that has called <tt>Thread.join()</tt>
         * is waiting for a specified thread to terminate.
         进入该状态的线程需要等待其他线程做出一些特定动作(通知或中断)。
         */
        WAITING,

        /**
         * Thread state for a waiting thread with a specified waiting time.
         * A thread is in the timed waiting state due to calling one of
         * the following methods with a specified positive waiting time:
         * <ul>
         *   <li>{@link #sleep Thread.sleep}</li>
         *   <li>{@link Object#wait(long) Object.wait} with timeout</li>
         *   <li>{@link #join(long) Thread.join} with timeout</li>
         *   <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li>
         *   <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li>
         * </ul>
         该状态不同于WAITING,它可以在指定的时间后自行返回。
         */
        TIMED_WAITING,

        /**
         * Thread state for a terminated thread.
         * The thread has completed execution.
         表示该线程已经执行完毕。
         */
        TERMINATED;
    }

线程的状态图:

线程状态图

BLOCKED和WAITING的区别

状态形成的调用方法不同

阻塞状态是线程阻塞在进入synchronized关键字修饰的方法或代码块(获取锁)时的状态。

Java线程之Synchronized用法

BLOCKED当前线程还处于活跃状态,只是在阻塞等待其他线程使用完某个资源锁;

WAITING是因为自身调用了Object.wait()或者是Thread.join()又或者是LockSupport.park()而进入等待状态,只能等待其他线程执行某个特定的动作才能唤醒,比如线程自身调用了Object.wait()而进入WAITING状态之后,则需要等待另一个线程执行Object.notify()或者Object.notifyAll()才能被唤醒。

start()和run()的区别

public synchronized void start() {
    /**
     * This method is not invoked for the main method thread or "system"
     * group threads created/set up by the VM. Any new functionality added
     * to this method in the future may have to also be added to the VM.
     *
     * A zero status value corresponds to state "NEW".
     */
    if (threadStatus != 0)
        throw new IllegalThreadStateException();

    /* Notify the group that this thread is about to be started
     * so that it can be added to the group's list of threads
     * and the group's unstarted count can be decremented. */
    group.add(this);

    boolean started = false;
    try {
        start0();
        started = true;
    } finally {
        try {
            if (!started) {
                group.threadStartFailed(this);
            }
        } catch (Throwable ignore) {
            /* do nothing. If start0 threw a Throwable then
              it will be passed up the call stack */
        }
    }
}

start()方法可以开启多线程,让线程从NEW状态转换成RUNNABLE状态。不能被多次调用,否则会抛出java.lang.lllegalStateExcaption;

run()方法只是一个普通的方法,可以被多次调用。

线程优先级

/**
     * 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;

设置线程的优先级

/**
 * Changes the priority of this thread.
 * <p>
 * First the <code>checkAccess</code> method of this thread is called
 * with no arguments. This may result in throwing a
 * <code>SecurityException</code>.
 * <p>
 * Otherwise, the priority of this thread is set to the smaller of
 * the specified <code>newPriority</code> and the maximum permitted
 * priority of the thread's thread group.
 *
 * @param newPriority priority to set this thread to
 * @exception  IllegalArgumentException  If the priority is not in the
 *               range <code>MIN_PRIORITY</code> to
 *               <code>MAX_PRIORITY</code>.
 * @exception  SecurityException  if the current thread cannot modify
 *               this thread.
 * @see        #getPriority
 * @see        #checkAccess()
 * @see        #getThreadGroup()
 * @see        #MAX_PRIORITY
 * @see        #MIN_PRIORITY
 * @see        ThreadGroup#getMaxPriority()
 */
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);
    }
}

线程的常用方法

join()方法 一个线程调用other.join()。这时候当前线程会让出执行权给other线程,直到other线程执行完或者过了超时时间之后再继续执行当前线程。

/**
     * Waits at most {@code millis} milliseconds for this thread to
     * die. A timeout of {@code 0} means to wait forever.
     *
     * <p> This implementation uses a loop of {@code this.wait} calls
     * conditioned on {@code this.isAlive}. As a thread terminates the
     * {@code this.notifyAll} method is invoked. It is recommended that
     * applications not use {@code wait}, {@code notify}, or
     * {@code notifyAll} on {@code Thread} instances.
     *
     * @param  millis
     *         the time to wait in milliseconds
     *
     * @throws  IllegalArgumentException
     *          if the value of {@code millis} is negative
     *
     * @throws  InterruptedException
     *          if any thread has interrupted the current thread. The
     *          <i>interrupted status</i> of the current thread is
     *          cleared when this exception is thrown.
     */
    public final synchronized void join(long millis)
    throws InterruptedException {
        long base = System.currentTimeMillis();
        long now = 0;

        if (millis < 0) {
            throw new IllegalArgumentException("timeout value is negative");
        }

        if (millis == 0) {
            while (isAlive()) {
                wait(0);
            }
        } else {
            while (isAlive()) {
                long delay = millis - now;
                if (delay <= 0) {
                    break;
                }
                wait(delay);
                now = System.currentTimeMillis() - base;
            }
        }
    }

其底层方法还是使用wait()方法

未使用join()

public class ThreadExample {
    public static void main(String[] args) {
        Thread thread=new Thread(()->{
            for (int i = 1; i < 6; i++) {
                try{
                    Thread.sleep(1000);
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
                System.out.println("子线程睡眠"+i+"秒");
            }
        });
        thread.start();
        for (int i = 1; i < 4; i++) {
            try{
                Thread.sleep(1000);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
            System.out.println("主线程睡眠"+i+"秒");
        }
    }
}

子线程睡眠1秒
主线程睡眠1秒
子线程睡眠2秒
主线程睡眠2秒
子线程睡眠3秒
主线程睡眠3秒
子线程睡眠4秒
子线程睡眠5

使用join()

public class ThreadExample {
    public static void main(String[] args) throws InterruptedException {
        Thread thread=new Thread(()->{
            for (int i = 1; i < 6; i++) {
                try{
                    Thread.sleep(1000);
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
                System.out.println("子线程睡眠"+i+"秒");
            }
        });
        thread.start();
        thread.join(2000);
        for (int i = 1; i < 4; i++) {
            try{
                Thread.sleep(1000);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
            System.out.println("主线程睡眠"+i+"秒");
        }
    }
}
子线程睡眠1秒
子线程睡眠2秒
主线程睡眠1秒
子线程睡眠3秒
主线程睡眠2秒
子线程睡眠4秒
主线程睡眠3秒
子线程睡眠5

添加join()方法后,主线程会先等子线程执行2s之后才继续执行

yield()方法表示给线程调度器一个当前线程愿意出让CPU使用权的暗示,但是线程调度器可能会忽略这个暗示。

public class ThreadExample2 {
    public static void main(String[] args) throws InterruptedException {
        Runnable runnable=new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    System.out.println("线程"+Thread.currentThread().getName());
                    if(i==5)
                        Thread.yield();
                }

            }
        };
        Thread t1=new Thread(runnable,"T1");
        Thread t2=new Thread(runnable,"T2");
        t1.start();
        t2.start();

    }
}

代码执行多次之后,每次执行的结果都不相同。这是因为yield()执行非常不稳定,线程调度器不一定会采纳yield()出让CPU使用权的建议。

Thread中sleep和yield方法的区别

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值