線程池-基礎類

1.UnSafe類

UnSafe類:用於執行低級別、不安全操作的方法集合,其通過直接操作內存來保證線程安全。Unsafe和ByteBuff都能用於是獲取非堆內存,但UnSafe保證了對非堆內存的操作是線程安全的,而ByteBuff不能保證。
並且其可以不用調用類的構造函數從而直接反序列化對象等。

2.Thread類

關鍵Field: ThreadGroup g 、Runnable target、線程名 name、初始線程棧大小stackSize、AccessControlContext acc權限控制對象
最好的調用方式:

指定運行的target對象和線程名(用於jvm進行標識)
ThreadGroup使用默認的ThreadGroup
public Thread(Runnable target, String name) {
        init(null, target, name, 0);
    }
  1. ThreadGroup主要用於管理線程(已經啓動的線程,啓動線程數、未啓動線程數等),通常使用默認值爲與主線程屬於同一個組。
    默認值:main,其父group爲system。幾個重要屬性:int nUnstartedThreads = 0; int nthreads; Thread threads[];
SecurityManager security = System.getSecurityManager();
security.getThreadGroup();
************等價於****************
Thread.currentThread().getThreadGroup()
  1. daemon 是否是守護進程默認是false。如果是非守護進程,JVM進程必須等待所有的非守護進程完成後才能結束。如果是守護進程,那麼當沒有非守護進程存在的時候,JVM會直接退出,不管非守護進程是否完成。因此守護進程一般用於後臺進程,可以隨時中斷,如分佈式系統中的心跳檢測線程等。
  2. tid 線程號,JVM進程中用於唯一的標識一個線程。
  3. Thread start方法,其維護ThreadGroup中的信息外,最重要的是start0()方法,其調用本地操作系統的函數。爲多線程的實現提供本地操作系統的支持。同理interrupt和interrupt0方法。
  4. start()、interrupt()、stop()、suspend()、resume()等方法能夠改變線程的執行狀態,都是因爲其有對應的native同操作系統進行交互。
類級別的鎖,保證線程安全性和唯一性
/* For generating thread ID */
    private static long threadSeqNumber;

tid = nextThreadID();
private static synchronized long nextThreadID() {
        return ++threadSeqNumber;
    }
public
class Thread implements Runnable {

public Thread(ThreadGroup group, Runnable target, String name,
                  long stackSize) {
        init(group, target, name, stackSize);
    }

    private void init(ThreadGroup g, Runnable target, String name,
                      long stackSize, AccessControlContext acc) {
        if (name == null) {
            throw new NullPointerException("name cannot be null");
        }

        this.name = name.toCharArray();

        Thread parent = currentThread();
        SecurityManager security = System.getSecurityManager();
        if (g == null) {
            /* Determine if it's an applet or not */

            /* If there is a security manager, ask the security manager
               what to do. */
            if (security != null) {
                g = security.getThreadGroup();
            }

            /* If the security doesn't have a strong opinion of the matter
               use the parent thread group. */
            if (g == null) {
                g = parent.getThreadGroup();
            }
        }

        /* checkAccess regardless of whether or not threadgroup is
           explicitly passed in. */
        g.checkAccess();

        /*
         * Do we have the required permissions?
         */
        if (security != null) {
            if (isCCLOverridden(getClass())) {
                security.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
            }
        }

        g.addUnstarted();

        this.group = g;
        this.daemon = parent.isDaemon();
        this.priority = parent.getPriority();
        if (security == null || isCCLOverridden(parent.getClass()))
            this.contextClassLoader = parent.getContextClassLoader();
        else
            this.contextClassLoader = parent.contextClassLoader;
        this.inheritedAccessControlContext =
                acc != null ? acc : AccessController.getContext();
        this.target = target;
        setPriority(priority);
        if (parent.inheritableThreadLocals != null)
            this.inheritableThreadLocals =
                ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
        /* Stash the specified stack size in case the VM cares */
        this.stackSize = stackSize;

        /* Set thread ID */
        tid = nextThreadID();
    }

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


    **private native void start0();**

public void interrupt() {
        if (this != Thread.currentThread())
            checkAccess();

        synchronized (blockerLock) {
            Interruptible b = blocker;
            if (b != null) {
                interrupt0();           // Just to set the interrupt flag
                b.interrupt(this);
                return;
            }
        }
        interrupt0();
    }

@Override
    public void run() {
        if (target != null) {
            target.run();
        }
    }
}

3 ThreadGroup類

線程組表示一個線程的集合。此外,線程組也可以包含其他線程組。線程組構成一棵樹,在樹中,除了初始線程組外,每個線程組都有一個父線程組。允許線程訪問有關自己的線程組的信息,但是不允許它訪問有關其線程組的父線程組或其他任何線程組的信息。
一般程序啓動都至少有兩個線程組:system線程組(parent=null),有JVM實例化,其做爲main線程組的parent。
每個線程在調用構造函數的時候,必須綁定一個線程組,默認其獲取實例化該線程對象的線程的線程組,大部分情況下都爲main線程組。並且會調用線程組的g.addUnstarted();將未啓動的線程數量+1。在調用線程的start方法時,group.add(this);將啓動的線程放thread 數組中threads[nthreads] = t; 並且將啓動線程+1,未啓動線程-1;nthreads++;nUnstartedThreads–;

4 ThreadFactory類

ThreadFactory是一個工廠類,用於產生新的線程。
其中比較重要的是:
group = (s != null) ? s.getThreadGroup() :
Thread.currentThread().getThreadGroup();
namePrefix = “pool-” +
poolNumber.getAndIncrement() +
“-thread-“;
group用於定義管理該線程工廠產生的線程的線程組,大部分時候採用默認值即main線程組。
namePrefix :表明線程的名字,一般在實現自己的線程工廠的時候,需要採用有意義的線程池名字,在調試的時候能夠比較好的區分。

static class DefaultThreadFactory implements ThreadFactory {
        private static final AtomicInteger poolNumber = new AtomicInteger(1);
        private final ThreadGroup group;
        private final AtomicInteger threadNumber = new AtomicInteger(1);
        private final String namePrefix;

        DefaultThreadFactory() {
            SecurityManager s = System.getSecurityManager();
            group = (s != null) ? s.getThreadGroup() :
                                  Thread.currentThread().getThreadGroup();
            namePrefix = "pool-" +
                          poolNumber.getAndIncrement() +
                         "-thread-";
        }

        public Thread newThread(Runnable r) {
            Thread t = new Thread(group, r,
                                  namePrefix + threadNumber.getAndIncrement(),
                                  0);
            if (t.isDaemon())
                t.setDaemon(false);
            if (t.getPriority() != Thread.NORM_PRIORITY)
                t.setPriority(Thread.NORM_PRIORITY);
            return t;
        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章