Java Thread source code analysis

Source: Internet
Author: User

 

 

It takes a long time for a thread to do something. The sub-thread under the main thread is a proxy mode. The main thread divides the proxy to the sub-thread, and the sub-thread helps the main thread to complete some tasks. Today, let's take a look at the thread source code for system learning.

1. The thread has six states.

Public enum State {
/**
* The thread has been created, but has never been started.
*/
NEW,
/**
* The thread may be run.
*/
RUNNABLE,
/**
* The thread is blocked and waiting for a lock.
*/
BLOCKED,
/**
* The thread is waiting.
*/
WAITING,
/**
* The thread is waiting for a specified amount of time.
*/
TIMED_WAITING,
/**
* The thread has been terminated.
*/
TERMINATED
}

NEW: The instance has not been created yet.

RUNNABLE: executable

BLOCKED: block status, waiting to hold the lock

WAITING: Processing Wait Status

TIMED_WAITING: Wait for some time

TERMINATED

/**
* The maximum priority value allowed for a thread.
*/
Public static final int MAX_PRIORITY = 10;


/**
* The minimum priority value allowed for a thread.
*/
Public static final int MIN_PRIORITY = 1;


/**
* The normal (default) priority value assigned to threads.
*/
Public static final int NORM_PRIORITY = 5;

2. They are the maximum, minimum, and default priorities that can be set by the thread. The higher the level, the higher the execution speed.

/**
* Holds the thread's ID. We simply count upwards, so
* Each Thread has a unique ID.
*/
Private long id;

3. Each thread has a unique ID.

Public Thread (){
Create (null, 0 );
}

Private void create (ThreadGroup group, Runnable runnable, String threadName, long stackSize ){
Thread currentThread = Thread. currentThread ();
If (group = null ){
Group = currentThread. getThreadGroup ();
}


If (group. isDestroyed ()){
Throw new IllegalThreadStateException (Group already destroyed );
}


This. group = group;


Synchronized (Thread. class ){
Id = ++ Thread. count;
}


If (threadName = null ){
This. name = Thread-+ id;
} Else {
This. name = threadName;
}


This.tar get = runnable;
This. stackSize = stackSize;


This. priority = currentThread. getPriority ();


This. contextClassLoader = currentThread. contextClassLoader;


// Transfer over InheritableThreadLocals.
If (currentThread. inheritableValues! = Null ){
InheritableValues = new ThreadLocal. Values (currentThread. inheritableValues );
}
// Add ourselves to our ThreadGroup of choice
This. group. addThread (this );
}

4. Initialize an empty thread, obtain the currently running thread group, Set id, name, execution thread runnable, pool size stackSize, priority, and add it to the thread group, this is a Thread with no parameters. Normally there should be four parameters: ThreadGroup, Runnable, threadName, and stackSize. Generally, if threadName is null, NullPointerException is returned. stackSize is 0 by default.

/**
* Destroys the aggreger without any monitor cleanup.
*
* @ Deprecated Not implemented.
*/
@ Deprecated
Public void destroy (){
Throw new NoSuchMethodError (Thread. destroy (); // TODO Externalize ???
}

5. The destroy method has been abandoned in Java 7.

Public void interrupt (){
Synchronized (interruptActions ){
For (int I = interruptActions. size ()-1; I> = 0; I --){
InterruptActions. get (I). run ();
}
}

VMThread vmt = this. vmThread;
If (vmt! = Null ){
Vmt. interrupt ();
}
}

6. Stop the current thread. If the thread is in the wait, join, or sleep status, an exception is reported.

Public final boolean isAlive (){
Return (vmThread! = Null );
}

7. Check whether the thread is dead. It mainly determines whether the VM thread is dead. Of course, the current thread is obtained through VMThread. currentThread () and the next step to obtain which of the six states the current thread is in.

Public State getState (){
// TODO This is ugly and shoshould be implemented better.
VMThread vmt = this. vmThread;


// Make sure we have a valid reference to an object. If native code
// Deletes the reference we won't run into a null reference later.
VMThread thread = vmThread;
If (thread! = Null ){
// If the Thread Object became invalid or was not yet started,
// GetStatus () will return-1.
Int state = thread. getStatus ();
If (state! =-1 ){
Return VMThread. STATE_MAP [state];
}
}
Return hasBeenStarted? Thread. State. TERMINATED: Thread. State. NEW;
}

Public final void join () throws InterruptedException {
VMThread t = vmThread;
If (t = null ){
Return;
}


Synchronized (t ){
While (isAlive ()){
T. wait ();
}
}
}

8. join blocks the current thread and puts it in a waiting state, because the execution time of the subthread may be longer than that of the main thread, therefore, join is the main thread that needs to be destroyed after it is executed. Of course, you can also add the join parameter (long millis, int nanos) to wait for N seconds for N milliseconds. If it is already in the join method, InterruptedException is reported.

Public final void setDaemon (boolean isDaemon ){
If (hasBeenStarted ){
Throw new IllegalThreadStateException (Thread already started.); // TODO Externalize?
}


If (vmThread = null ){
Daemon = isDaemon;
}
}

9. It is set as the daemon thread. The required runnable before execution will be executed when other non-daemon threads are running.

Public final void setPriority (int priority ){
If (priority <Thread. MIN_PRIORITY | priority> Thread. MAX_PRIORITY ){
Throw new IllegalArgumentException (Priority out of range); // TODO Externalize?
}


If (priority> group. getMaxPriority ()){
Priority = group. getMaxPriority ();
}


This. priority = priority;


VMThread vmt = this. vmThread;
If (vmt! = Null ){
Vmt. setPriority (priority );
}
}

10. The priority is mainly set through VMThread. Note that the highest priority is set to 10 and the lowest priority is 1. Otherwise, IllegalArgumentException is reported.

Public static void sleep (long millis, int nanos) throws InterruptedException {

        VMThread.sleep(millis, nanos);
}

 

11. Run sleep. If the sleep is interrupted by interrupt, InterruptedException is reported.

/**
* Starts the new Thread of execution.run()Method
* The specified er will be called by the specified er Thread itself (and not
* Thread callingstart()).
*
* @ Throws IllegalThreadStateException if the Thread has been started before
*
* @ See Thread # run
*/
Public synchronized void start (){
If (hasBeenStarted ){
Throw new IllegalThreadStateException (Thread already started.); // TODO Externalize?
}


HasBeenStarted = true;


VMThread. create (this, stackSize );
}

12. The thread starts execution. If start has been executed, IllegalThreadStateException is reported.

@ Deprecated
Public final synchronized void stop (Throwable throwable ){
Throw new UnsupportedOperationException ();
}

13. stop method abandon

Public static void yield (){
VMThread. yield ();
}

14. Give way to another thread that is ready to run and let it execute first

The difference between join and yield is described in the previous section:

Functions of join and yield in Java

 

 

 

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.