Java Thread你应该知道的一切

2018-03-31  本文已影响0人  吕洪磊

线程的知识点真的很多,想要全面掌握,需要日积月累,今天就请大家跟随我,一起走进Thread的世界。
想要走进Thread,那么就从源码开始吧。

Thead State 线程的状态

这个知识点,是你必须知道的,线程那些状态呢?

public enum State {
        /**
         * Thread state for a thread which has not yet started.
         */
        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.
         */
        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>
         */
        TIMED_WAITING,

        /**
         * Thread state for a terminated thread.
         * The thread has completed execution.
         */
        TERMINATED;
    }

上面的枚举类是Thread内部枚举,里面包含了线程的几种状态,那么我们来看看,都是什么状态。

NEW

Thread state for a thread which has not yet started

public class ThreadTest {
    public static void main(String[] args){
        Thread thread = new Thread();
        Thread.State state = thread.getState();
        System.out.println(state.toString());
    }
}

当运行以上代码的时候,打印结果是 NEW,这样我们可以理解,线程创建以后,在没有调用start方法以前,Thread的状态是NEW.

RUNNABLE

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.

public class ThreadTest {
    public static void main(String[] args){
        Thread thread = new Thread();
        thread.start();
        Thread.State state = thread.getState();
        System.out.println(state.toString());
    }
}

当运行以上代码的时候,打印的结果是RUNNABLE,当前线程从NEW状态转到了RUNNABLE状态。
在网上看到好多人在写Thread状态的时候,还有运行中状态,这是不正确的,如何用代码证明呢?

public class ThreadTest {
    public static void main(String[] args){
        Thread thread = new Thread(new MyThread());
        thread.start();

        Thread.State state = thread.getState();
        System.out.println(state.toString());
    }

    static class MyThread implements Runnable{

        public void run() {
            int count = 0;
            for (int i=0;i<10000;i++){
                count = count+i;
                System.out.println(Thread.currentThread().getState().toString());
            }
        }
    }
}

运行以上代码,你会发现,线程根本没有所谓的运行中的状态,CPU已经计算结果了

BLOCKED

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}
阻塞状态,当前线程在等待一个monitor lock。
1.调用synchronized,使线程进入阻塞状态。
2.调用wait方法,使线程进入阻塞状态。

WAITING

使线程进入WAITING状态的几种场景:
1.调用了wait方法,没有设置过期时间
2.调用Thread.join方法,没有设置过期时间
3.调用了LockSupport#park

TIMED_WAITING

使线程进入TIMED_WAITING状态的几种场景:
1.调用了Thread.sleep方法
2.调用了Object.wati方法,设置了过期时间
3.调用了Thread.join方法,设置了过期时间
4.调用了LockSupport#parkNanos
5.调用了LockSupport#parkUntil

TERMINATED

线程已经执行完成,就进入了线程终止状态。

线程的优先级

当多个线程的优先级相同的时候,它们使抢夺CPU资源。如果,你想让某个线程有限执行,你就可以设置它的优先级,可以通过Thread.setPriority设置线程优先级,优先级一共有10个级别,线程默认的优先级使5

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

守护线程

上一篇下一篇

猜你喜欢

热点阅读