Java Thread Series (ii) threading State

Source: Internet
Author: User
Tags thread class

Java Thread Series (ii) Threads state One, five states of threads

    1. New state: A new Thread object has been created and has not been started.
    2. Ready state (Runnable): Also known as the operational state. After the thread object is created, other threads call the object's start () method. The state of the thread is located in a pool of running threads that becomes operational and waits for the CPU to be used.
    3. Running state (Running): The ready state of the thread gets the CPU and executes the program code.
    4. Blocking state (Blocked): The blocking state is a temporary stop when the thread abandons the CPU usage for some reason. Until the thread is in a ready state, the opportunity to go to the running state is reached. There are three types of blocking:
      • Wait for blocking: The running thread executes the wait () method, and the JVM puts the thread into the waiting pool.
      • Synchronous blocking: When a running thread acquires a synchronization lock on an object, the JVM puts the thread into the lock pool if the synchronization lock is occupied by another thread.
      • Other blocking: The running thread executes the sleep () or join () method, or when an I/O request is made, the JVM will place the thread in a blocked state. When the sleep () state times out, join () waits for the thread to terminate or time out, or the I/O process finishes, the thread is re-entered in a ready state.
    5. Dead State (Dead): The thread finishes executing or exits the run () method because of an exception, and the thread ends the life cycle.
Second, thread scheduling

(1) Thread priority

Java threads have priority, and high-priority threads get more running opportunities.

The priority of a Java thread is expressed in integers, and the value range is the following three static constants for the 1~10,thread class:

staticint MAX_PRIORITY     // 线程可以具有的最高优先级,取值为 10。staticint MIN_PRIORITY     // 线程可以具有的最低优先级,取值为 1。staticint NORM_PRIORITY    // 分配给线程的默认优先级,取值为 5。

The SetPriority () and GetPriority () methods of the thread class are used to set and get the priority of the thread, respectively.

Each thread has a default priority. The default priority for the primary thread is thread.norm_priority.
The priority of a thread has an inheritance relationship, such as the B thread created in a thread, then B will have the same priority as a.
The JVM provides 10 thread priorities, but does not map well with common operating systems. If you want the program to be portable to each operating system, you should only use the Thread class with the following three static constants as priority, which ensures that the same precedence is used for the same scheduling.

(2) Thread sleep

The Thread.Sleep (long Millis) method causes the thread to go to the blocking state. The Millis parameter sets the time to sleep, in milliseconds. When sleep is over, it becomes ready (Runnable) state. Sleep () platform portability is good.

(3) Thread wait

The wait () method in the object class causes the current thread to wait until another thread calls the Notify () method of this object or the Notifyall () Wake method. This two wake-up method is also a method in the Object class, and behaves equivalent to calling wait (0).

(4) Threading concessions

The Thread.yield () method pauses the currently executing thread object and gives the execution opportunity to the same or higher priority thread.

(5) Thread join

Join () method, waiting for other threads to terminate. Invoking the Join () method of another thread in the current thread, the current thread goes into a blocking state until the other process finishes running, and the current thread is then turned into a ready state by blocking.

(6) Thread wake-up

The Notify () method in the object class wakes up a single thread that waits on this objects monitor. If all threads are waiting on this object, then one of the threads is chosen to wake up. The choice is arbitrary and occurs when a decision is made on the implementation. The thread waits on the object's monitor by calling one of the wait methods. Until the current thread discards the lock on this object, it can continue to execute the awakened thread. The awakened thread competes with all other threads that are actively synchronizing on the object, for example, the thread that wakes up does not have a reliable privilege or disadvantage as the next thread that locks the object. A similar approach also has a notifyall () that wakes up all the threads waiting on this object monitor.

Note: Thread suspend () and resume () Two methods have been abolished in JDK1.5 and are no longer introduced. Because there is a deadlock tendency.

Three, the common function description

(1) Thread.Sleep (long Millis)

Sleep () lets the currently executing thread hibernate (paused) within the specified number of milliseconds

Sleep () cannot change the machine lock of an object, so when the sleep () method is called in a Synchronized block, the thread sleeps, but the object's machine lock and the wood is freed, and the other thread cannot access the object (even if it is asleep, it holds the object lock).

After the sleep () sleep time expires, the thread does not necessarily execute immediately, because other threads may be running and are not scheduled to abort execution unless the thread has a higher priority.

(2) Join ()

 Public classJointestextendsThread {@Override     Public void Run() {Try{Thread.Sleep( -); System. out.println("Child Thread:"+ Thread.CurrentThread().GetName()); }Catch(Interruptedexception e)        {            ; }    } Public Static void Main(string[] args)throwsinterruptedexception {Jointest T =New jointest(); T.Start(); T.Join();//(1)System. out.println("Main thread:"+ Thread.CurrentThread().GetName()); }}
    1. T.join () blocks the current thread, that is, the main thread, which means that the main thread waits for the child thread to finish executing before it continues.

(3) Thread.yield ()

The Thread.yield () method acts by suspending the currently executing thread object and executing other threads.

What Thread.yield () should do is get the current running thread back to the operational state to allow other threads with the same priority to get a run chance. Therefore, the purpose of using Thread.yield () is to allow appropriate rotation between threads of the same priority. However, in practice there is no guarantee that yield () will be compromised, as the thread of the concession may be checked again by the thread scheduler.

(4) SetPriority ()

The priority of the thread to be rerouted.

1510

(5) Interrupt ()

Don't think it's interrupting a thread! It is just a line thread that sends an interrupt signal that allows the thread to throw an exception when it waits indefinitely, such as a deadlock, to end the thread, but if you eat the exception, the thread will not break!

(6) Wait ()

The wait () method is a method in the object class, and when a thread executes to the wait () method, it enters into a waiting pool associated with the object and loses (frees) the object's machine lock (temporarily loses the machine lock, wait (long timeout) Return the object lock after the timeout period, other threads can access;

Wait () wakes the threads in the current waiting pool using notify or notifyalll or specifying sleep time.

Wiat () must be placed in the synchronized block, otherwise the "java.lang.IllegalMonitorStateException" exception will be thrown when the program runtime.

Wait and sleep differences

Common:

    1. They are all in a multi-threaded environment and can block the specified number of milliseconds at the call of the program and return.
    2. Both wait () and sleep () can break the thread's suspend state through the interrupt () method, causing the thread to throw interruptedexception immediately.

If thread A wants to end thread B immediately, you can call the interrupt method on the thread instance that corresponds to threads B. If thread B is wait/sleep/join at the moment, thread B will immediately throw interruptedexception, and return directly in catch () {} to safely end the thread.

It is important to note that Interruptedexception is thrown from within the thread itself, not by the interrupt () method. When you call interrupt () on a thread, the thread does not throw interruptedexception at all if it is executing normal code. However, once the thread has entered wait ()/sleep ()/join (), the interruptedexception is immediately thrown.

Different points:

    1. Method of the Thread class: Sleep (), yield (), and so on. Method of object: Wait () and notify (), etc.
    2. Each object has a lock to control synchronization access. The Synchronized keyword can interact with the object's lock to achieve thread synchronization.
      The Sleep method does not release the lock, and the wait method frees the lock so that other threads can use the synchronization control block or method.
    3. Wait,notify and Notifyall can only be used in synchronous control methods or synchronization control blocks, and sleep can be used anywhere
    4. Sleep must catch exceptions, while wait,notify and notifyall do not need to catch exceptions

So the biggest difference between the Thread.Sleep () and the Object.wait () method is that when sleep () sleeps, it keeps the lock on the object and still holds it, while wait () releases the object lock when it sleeps. But wait () and sleep () can break the thread's suspend state through the interrupt () method, causing the thread to throw interruptedexception immediately (but not recommended).

Four, common thread noun explanation

Main thread: The threads generated by the JVM Invoker main ().

Current thread: This is an easy-to-confuse concept. Generally refers to the process obtained through Thread.CurrentThread ().

Background thread (daemon): Refers to a thread that provides services to other threads. The garbage collection thread of the JVM is a background thread. The difference between a user thread and a daemon thread is whether to wait for the main thread to end up dependent on the end of the main thread.

Foreground thread: Refers to the thread that accepts the background thread service, in fact the foreground background thread is linked together, just like the puppet and the behind-the-scenes manipulator's relationship. The Puppet is the foreground thread and the behind-the-scenes manipulator is a background thread. The thread created by the foreground thread is also the foreground thread by default. You can use the Isdaemon () and Setdaemon () methods to determine and set whether a thread is a background thread.

Some common methods of thread threading classes:

Thread.sleepisAlivejoinactiveCountenumeratecurrentThreadisDaemonsetDaemonsetNamewaitnotifysetPriority(): 设置一个线程的优先级。

Record a little bit every day. Content may not be important, but habits are important!

Java Thread Series (ii) threading State

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.