Java Concurrency---Thread source analysis __java

Source: Internet
Author: User
Tags thread class throwable volatile

In multithreaded programming, if you want to use threads to perform tasks, the easiest way to do this is to use the thread class to create a thread, and of course you can use a thread pool.
Threads are the units that are executed in the process, and the thread's resource overhead is relatively low relative to the process, so we typically create thread execution rather than process execution.
This article is not about the use of thread, but about the process of threading from creation to completion through the thread class. Inheritance System


The thread class implements the Runnable interface, so thread is not only a thread class, but also a special execution task class. Data Structure

  byte array of thread names private volatile char name[];
  Thread-priority private int priority;
  Private Thread THREADQ;
  Private long eetop;

  Whether the thread is Single step private Boolean single_step;

  is the daemon thread private Boolean daemon = false;

  /* JVM state */Private Boolean stillborn = false;

  Object of the Run method to execute private Runnable target;

  The thread group of this thread is private threadgroup group;

  /* The inherited accesscontrolcontext of this thread * * Private accesscontrolcontext Inheritedaccesscontrolcontext;

  Thread number private static int threadinitnumber; /* ThreadLocal values pertaining to this thread. 
   This map is maintained * by the ThreadLocal class.
  *///ThreadLocal related threadlocal.threadlocalmap threadlocals = null; * * Inheritablethreadlocal values pertaining to this thread.
 This map was * maintained by the Inheritablethreadlocal class.  * * Threadlocal.threadlocalmap inheritablethreadlocals = null;  * * The requested stack size for this thread, or 0 if the creator did * is not specify a stack size. It is up to the VM to does whatever it * likes with this number;
   Some VMs would ignore it.
  *///To the size of the stack set for this thread, the default is 0 private long stacksize;
   * * Jvm-private state this 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 '///initial state private volatile

  int threadstatus = 0;
   /** * the "argument supplied to" the "the" call to * Java.util.concurrent.locks.LockSupport.park. * Set by (private) java.util.concurrent.locks.LockSupport.setBlocker * accessed using Java.util.concurrent.locks.LockS

  Upport.getblocker */volatile Object parkblocker; /* The object in WHich this thread was blocked in a interruptible I/o * operation, if any.
   The blocker ' s interrupt method should is invoked * after setting this thread ' s interrupt status.

  * * Private volatile interruptible blocker;

  The lock object used for blocker is the private final object blockerlock = new Object ();
   /** * The minimum priority that a thread can have.
 *///Lowest priority public final static int min_priority = 1;
   /** * The default priority this is assigned to a thread.
  *///thread default execution priority is 5 public final static int norm_priority = 5;
   /** * The maximum priority that a thread can have. *///The highest priority of the thread execution is the public final static int max_priority = 10;

The properties above contain the basic properties of the thread, and thread is not an execution task, but rather as a thread unit that has an executable task target (Runnable type) inside, which we will explore in more detail in the latter approach.
Thread priority on different platforms, the corresponding system priority will be different, there may be multiple priority for the same system priority, high priority thread does not necessarily priority, which is interpreted by the JVM and provide reference to the system. thread State (life cycle)

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 * the "is" executing in the Java virtual machine but it may * being waiting for other Reso
     Urces from the operating system * such as processor.
     */RUNNABLE,/** * thread state for a thread blocked waiting for a monitor lock. * A thread in the blocked ' waiting for a monitor lock * to enter a synchronized block/method or * reente
     R a synchronized Block/method after calling/BLOCKED,/** * thread state for a waiting thread.
     * * Waiting,/** * thread state for a waiting thread with a specified waiting time.
     * * timed_waiting,/** * thread state for a terminated thread.
     * The thread has completed execution.
* * terminated; }

The state of the thread is new,runnable,blocked,waiting,timed_waiting,terminated and the official document is very detailed. Construction Method

1. Non-parametric construction

Public Thread () {
    init (null, NULL, "thread-" + nextthreadnum (), 0);
}

2, designated to perform the task

Public Thread (Runnable target) {
    init (null, Target, "thread-" + nextthreadnum (), 0);
}

3. Specify thread groups and perform tasks

Public Thread (Threadgroup Group, Runnable target) {
    init (group, Target, "thread-" + nextthreadnum (), 0);
}

There are many other constructs that are not listed here, and in the constructor method, the Init method is invoked to initialize. Init method

private void Init (Threadgroup g, Runnable Target, String name, Long stacksize, AccessControlContext ACC)
    {if (name = = null) {throw new NullPointerException ("name cannot be null");
    //Set thread name this.name = Name.tochararray ();
    The current calling thread is the parent thread thread parent = CurrentThread ();
    SecurityManager security = System.getsecuritymanager (); Rity 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 are explicitly passed in. * * G.checkaccess (

    );
 * * Do we have the required permissions?    */if (security!= null) {if (Isccloverridden (GetClass ())) {Security.checkpermission (Subclas
        S_implementation_permission);

    } g.addunstarted ();
    This.group = g;
    Inherit the related property of the parent thread 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 ();
    Set Execution Task this.target = target;
    SetPriority (priority); if (parent.inheritablethreadlocals!= null) this.inheritablethreadlocals = threadlocal.createinherited
    Map (parent.inheritablethreadlocals);

    /* Stash The specified stack size in case the VM cares/this.stacksize = stacksize; /* Set Thread ID *//Setting Threads Id,nextthreadid ()The synchronous processing tid = Nextthreadid (); }

The constructor method is executed by the caller thread, so the caller thread will act as the parent thread, and the newly created thread inherits some of the properties of the parent thread. Run Method

Thread inherits the Runnable interface, then you need to implement the Run method.

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

The Run method in thread calls the Run method of the target task, and by simply calling the Run method does not create a thread to perform the task alone, as we can see from run in thread, to create a thread to perform the task, we need to call the thread's Start method. Start Method

/** * Causes this thread to begin execution;
 The Java Virtual Machine * Calls the Run method of this thread.
     */public synchronized void Start () {/** * the ' is not ' invoked for the ' main method thread or ' system ' * Group Threads Created/set up by the VM.
     Any new functionality added * "To" in "future may have to also is added to the VM."
     * A Zero status value corresponds to state "NEW".

    */if (threadstatus!= 0)//If the thread is not an initial state, then an exception is thrown throw new illegalthreadstateexception ();
     /* Notify The group This thread are about to being started * So, it can be added to the group ' s list of threads 
     * and the group ' s unstarted count can be decremented.

    /////Add the started thread to the thread group Group.add (this);
    Boolean started = false;
    try {start0 ();//Call local method started = true;
            Finally {try {if (!started) {group.threadstartfailed (this);
       } The catch (Throwable ignore) {/* does nothing. If Start0 threw a throwable then it'll be passed up the call stack/}}, private native Voi D start0 ();

The

Start method is synchronous (synchronized decoration), which checks the state of the thread before starting the thread, and throws an exception if the thread is not an initial state, so it is not feasible to call start multiple times. The
Start method is executed by the caller thread, and the JVM will invoke the thread's Run method, which results in the execution of two threads, one of which calls the thread execution of the start () method and the other thread that executes the Run method. sleep () method

/**
  * Causes the currently executing thread to sleep (temporarily cease
  * execution) for the specified number of M Illiseconds plus the specified
  * Number of nanoseconds, subject to the precision and accuracy of system
  * Timers A nd schedulers. The thread does not lose ownership to any
  * monitors.
  */public
 static void sleep (long millis, int Nanos)
 throws interruptedexception {
     if (Millis < 0) {
         thr ow new IllegalArgumentException ("Timeout value is negative");
     }
     if (Nanos < 0 | | Nanos > 999999) {
         throw new IllegalArgumentException (
                             "nanosecond timeout value out of RA Nge ");
     }
     if (Nanos >= 500000 | | (Nanos!= 0 && millis = 0)) {
         millis++;
     }
     Sleep (Millis);  Call local Sleep Method
 }

The function of the Sleep method allows the current thread to hibernate for a certain amount of time, and it is noteworthy that this period does not release the held lock .

# # #join () method

/**
 * Waits at most {@code Millis} milliseconds for this thread to
 * die. A timeout of {@code 0} means to wait forever.
 *
/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) {
         //waits until the target thread ends while
         (IsAlive ()) {wait
             (0);
         }
     } else {while
         (isAlive ()) {
             long delay = Millis-now;
             if (delay <= 0) {break
                 ;
             }
             Wait (delay); Timeout wait now
             = System.currenttimemillis ()-base;
         }
     }
 }

The calling thread waits for the invoked thread task to execute through the join method until it times out or terminates. Interrupt () method

public void Interrupt () {
    if (this!= thread.currentthread ())
        checkaccess ();
    Synchronous processing
    synchronized (blockerlock) {
        interruptible b = blocker;
        if (b!= null) {
            interrupt0 ();           Just to set the interrupt flag
            b.interrupt (this);
            return;
        }
    Interrupt0 (); Call local Method
}

The interrupt () method is to interrupt the current thread (set the interrupt flag bit), and the thread may throw a interuptedexeption when it detects that the interrupt flag bit is set, and the interrupt state of the thread is cleared, Usually interrupts can be a safer way to cancel a task (provided it is able to respond to interrupts). Summary

Through the simple analysis of the source code, to understand some of the use of thread and precautions, the whole process of thread analysis is more obvious, of course, the study of multithreading is just beginning, and not completely in-depth details, but through the analysis of the source code, know the thread of the overall creation of the general process, It will also be more handy for using thread.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.