Java併發學習筆記1 Thread 類

bilibili-Java併發學習筆記1 Thread 類

基於 java 1.8.0

P5_從Thread與Runnable說開去

  1. Thread 概覽

java.lang.Thread

public
class Thread implements Runnable {
    /* Make sure registerNatives is the first thing <clinit> does. */
    private static native void registerNatives();
    static {
        registerNatives();
    }

    private volatile String name;
    private int            priority;
    private Thread         threadQ;
    private long           eetop;

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

    /* Whether or not the thread is a daemon thread. */
    private boolean     daemon = false;

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

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

    /* The group of this thread */
    private ThreadGroup group;

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

    /* ThreadLocal values pertaining to this thread. This map is maintained
     * by the ThreadLocal class. */
    ThreadLocal.ThreadLocalMap threadLocals = null;

    /*
     * InheritableThreadLocal values pertaining to this thread. This map is
     * maintained by the InheritableThreadLocal class.
     */
    ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;

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

    /* Java thread status for tools,
     * initialized to indicate thread 'not yet started'
     */

    private volatile int threadStatus = 0;


    private static synchronized long nextThreadID() {
        return ++threadSeqNumber;
    }

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

線程 是程序中的執行線程。Java 虛擬機允許應用程序併發地運行多個執行線程。

每個線程都有一個優先級,高優先級線程的執行優先於低優先級線程。每個線程都可以或不可以標記爲一個守護程序。當某個線程中運行的代碼創建一個新 Thread 對象時,該新線程的初始優先級被設定爲創建線程的優先級,並且當且僅當創建線程是守護線程時,新線程纔是守護程序

當 Java 虛擬機啓動時,通常都會有單個非守護線程(它通常會調用某個指定類的 main 方法)。Java 虛擬機會繼續執行線程,直到下列任一情況出現時爲止:

  • 調用了 Runtime 類的 exit 方法,並且安全管理器允許退出操作發生。
  • 非守護線程的所有線程都已停止運行,無論是通過從對 run 方法的調用中返回,還是通過拋出一個傳播到 run 方法之外的異常。

每個線程都有一個標識名,多個線程可以同名。如果線程創建時沒有指定標識名,就會爲其生成一個新名稱。

  1. 線程優先級
    private int            priority;

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

最小值爲 1,最大值爲 10,缺省值爲 5,值越大,優先級越高;

    Thread thread1 = new Thread();
    thread1.setPriority(6);
  1. 守護線程

當且僅當創建線程是守護線程時,新線程纔是守護程序;啓動後不能再進行設置守護線程:

    Thread thread1 = new Thread();
    thread1.setPriority(6);
    thread1.start();
    thread1.setDaemon(true);
//        Exception in thread "main" java.lang.IllegalThreadStateException
//            at java.lang.Thread.setDaemon(Thread.java:1359)
//            at new_package.thread.p5.MyTest.main(MyTest.java:18)

守護線程又稱後臺線程,gc 線程其實就是一個守護線程,當只有守護線程存在,非守護線程全部停止時,jvm 會退出運行;

  1. 標識名

可以指定,否則使用缺省名稱;

    // 構造函數指定線程名稱
    Thread thread1 = new Thread("Thread-no39102");
    // 方法設置名稱
    thread1.setName("Thread-no39102");

缺省名稱

    public Thread() {
        init(null, null, "Thread-" + nextThreadNum(), 0);
    }
    // "Thread-" + nextThreadNum()

    /* For autonumbering anonymous threads. */
    private static int threadInitNumber;
    private static synchronized int nextThreadNum() {
        return threadInitNumber++;
    }
  1. ThreadGroup
    ThreadGroup threadGroup = new ThreadGroup("my-threadgroup-name");
    Thread thread2 = new Thread(threadGroup,"my-thread-name");
  1. Runnable
/*
 * @author  Arthur van Hoff
 * @see     java.lang.Thread
 * @see     java.util.concurrent.Callable
 * @since   JDK1.0
 */
@FunctionalInterface
public interface Runnable {
    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see     java.lang.Thread#run()
     */
    public abstract void run();
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章