Thread

2018-10-03  本文已影响7人  TebahplaX

概述

  1. Java线程映射到OS的线程
  2. 代码版本:oracle jdk 1.8
  3. java.lang.Thread implements Runnable
    /* Make sure registerNatives is the first thing <clinit> does. */
    private static native void registerNatives();
    static {
        registerNatives();
    }
    

说明:确保在创建线程对象执行<clinit>方法时,注册私有方法,关于此jni方法,暂时不知道,todo

属性字段

常用属性

private volatile String name;
private int            priority;

private boolean     daemon = false;

private Runnable target;

private ThreadGroup group;

ThreadLocal.ThreadLocalMap threadLocals = null;
ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;

其他属性

private Thread         threadQ;
private long           eetop;

/* Whether or not to single_step this thread. */
private boolean     single_step;

/* JVM state */
private boolean     stillborn = false;

/* What will be run. */
private Runnable target;

/* The context ClassLoader for this thread */
private ClassLoader contextClassLoader;

/* The inherited AccessControlContext of this thread */
private AccessControlContext inheritedAccessControlContext;

/* For autonumbering anonymous threads. */
private static int threadInitNumber;
private static synchronized int nextThreadNum() {
    return threadInitNumber++;
}    

/*
 * The requested stack size for this thread, or 0 if the creator did
 * not specify a stack size.  It is up to the VM to do whatever it
 * likes with this number; some VMs will ignore it.
 */
private long stackSize;

/*
 * JVM-private state that persists after native thread termination.
 */
private long nativeParkEventPointer;

/*
 * Thread ID
 */
private long tid;

/* For generating thread ID */
private static long threadSeqNumber;
private static synchronized long nextThreadID() {
    return ++threadSeqNumber;
}

/* Java thread status for tools,
 * initialized to indicate thread 'not yet started'
 */
private volatile int threadStatus = 0;

关于中断的属性

/**
 * The argument supplied to the current call to
 * java.util.concurrent.locks.LockSupport.park.
 * Set by (private) java.util.concurrent.locks.LockSupport.setBlocker
 * Accessed using java.util.concurrent.locks.LockSupport.getBlocker
 */
volatile Object parkBlocker;

/* The object in which this thread is blocked in an interruptible I/O
 * operation, if any.  The blocker's interrupt method should be invoked
 * after setting this thread's interrupt status.
 */
private volatile Interruptible blocker;
private final Object blockerLock = new Object();
/* Set the blocker field; invoked via sun.misc.SharedSecrets from java.nio code
 */
void blockedOn(Interruptible b) {
    synchronized (blockerLock) {
        blocker = b;
    }
}

说明:

  1. parkBlocker属性提供给LockSupport使用,提供现场信息
  2. blocker属性提供给可中断IO使用,java.nio使用

线程状态

线程状态,Thread内部枚举

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

线程的状态转换如下图


线程生命周期.png

构造器

各种构造器, 会调用init()方法

方法

常用方法

  1. 当前线程
    public static native Thread currentThread();
    会调用jvm/os,todo
  2. 线程启动
    public synchronized void start();
    调用jni start0()方法,jvm/os,todo
  3. 线程运行
    @Override
    public void run() {
        if (target != null) {
            target.run();
        }
    }
    
  4. Thread
    1. yield():通知os的scheduler,当前线程放弃时间片
    2. join()
      join(...)
      1. 底层使用Object类 wait()/notify()/notifyAll()
      2. 若中断,清除中断状态,抛出异常
    3. sleep(...)
      若中断,清除中断状态,抛出异常
  5. Object
    1. wait()
      wait(...)
      若中断,清除中断状态,抛出异常
    2. notify()
      notifyAll()
  6. LockSupport
    1. park()
      park(...)
      parkNanos(...)
      parkUntil(...)
      若中断,直接返回,不清除中断状态,不抛异常
    2. unpark()

弃用方法

关于停止线程,在线程中断中说明,todo

  1. stop():不安全
  2. suspend():容易死锁
  3. resume():容易死锁

关于中断

  1. interrupt():调用jni interrupt0(),调用jvm/os,todo
    1. wait(...)/join(...)/sleep(...),清除中断状态,抛出异常
    2. InterruptibleChannel阻塞,channel关闭,设置中断状态
    3. Selector阻塞,select()方法返回,设置中断状态
  2. isIntettupted()
  3. interrupted()
    返回中断状态,若中断,清除中断状态
上一篇下一篇

猜你喜欢

热点阅读