Java Multi-Threading understanding

Source: Internet
Author: User

Once a thread is created, it is always in one of the 4 states of its life cycle. The state of the thread indicates the activity that this thread is currently working on, and the state of the thread can be controlled by the program, which means that the thread can be manipulated to change state. These actions include start (start), terminate (stop), sleep, suspend (suspend), resume, wait (wait), and notification (notify). Each operation corresponds to a method, which is provided by the package Java.lang.
① Create (new) state
If you create a thread without starting it, the thread is in the created state. For example, after the following statement is executed, the system has a thread mythread that is in the creation State:
Thread mythread= new Mythreadclass ();
where Mythreadclass () is a subclass of thread, and thread is provided by the Java system's Java.lang package. The thread in the creation State has not yet obtained the resources it deserves, so this is an empty thread. The system assigns resources to a thread only after it has been started (start).
② Operational (runnable) status
If you initiate a thread that is in a created state, the thread enters the operational state. The MyThread thread created earlier is still used as an example with the following statement: Mythread.start (); The thread mythread into the operational state. The above statement essentially calls the thread body, the run () method.
A thread that is in a running state only indicates that it has a running condition, but that the operational state is not necessarily a running state. Because running multithreaded programs in a single-processor system, it is true that only one thread is running at a time, and often multiple threads in the system are in a running state. The system enables all the running threads to share the processor through fast switching and scheduling, resulting in multi-threaded concurrency running on the macro.
As can be seen, whether a thread is running or not, in addition to being in a running state, depends on the scheduling of the system.
There are several operations that can be performed in a running state, most commonly from the run () method to exit gracefully and end the thread and go into extinction state. In addition, you can do the following:
Suspend operation, by calling the Suspend method to implement;
Sleep operations, by calling the sleep method to achieve;
Wait for the operation, by calling the wait method to implement;
The concession operation is achieved by invoking the yield method;
Terminates the operation by calling the Stop method.
The previous three operations will cause a thread that is in a running state to enter a non-operational state. For example, take the mythread thread as an example, and then use the following statement when it is in a running state:
Mythreadsleep (5000);
Call the sleep method to make the mythread thread sleep for 5 seconds (5000 milliseconds). Within 5 seconds, this thread cannot be scheduled to run by the system, and after 5 seconds, the mythread thread wakes up and automatically returns to the operational state.
If a thread goes to a non-operational state by performing a pending operation, it must be called a resume operation before the thread can return to the operational state.
A concession operation is another thread that enables a thread to forward CPU control to a peer priority in advance.
A thread that is in a running state can also make it extinct by calling the Stop method.
③ not operational (not runnable) status
The non-operational state is transformed by the operational state. A thread that is in a running state that enters a non-operational state if it encounters a suspend (suspend) operation, sleep operation, or waiting (wait) operation. In addition, if a thread is associated with an I/O operation, then when I am executing the I/o instruction, the thread is blocked because the peripheral speed is much lower than the processor speed, thus entering a non-operational state, and the thread will automatically return to the operational state only after the peripheral has completed the input/output. When a thread enters a non-operational state, it can return to a functioning state. There are usually three ways to get it back to a functioning state.
One is automatic recovery.
A thread that enters a non-operational state through sleep operation automatically resumes to a running state after a specified sleep time, and a thread that enters a non-operational state due to I/O blocking is automatically restored to the operational state after the peripheral completes the I/O operation.
The second is to restore it using the restore (Resume) method.
If a thread enters a non-operational state from the operational state due to a pending (suspend) operation, it must be restored to a running state with a resume operation.
The third is to use the notification (notify or notiyA11) method to restore it.
If a thread that is in a running state is in a non-operational state due to the wait (wait) operation surface, you must call the Notify method or the Notifyall method to restore it to a running state. The wait operation is often performed because the thread waits for a condition variable, and when this condition variable is obtained, the thread can be restored to a running state by the Notify or Notifyall method.
Each of the ways to recover to a functioning state is targeted and cannot be crossed. For example, a recovery operation for a thread that has entered a non-operational state due to blocking will be invalid.
In a non-operational state, it can also be terminated by a stop operation to enter the extinction state.
④ extinction (dead) state
A thread can enter the extinction state by terminating (stop) operations by any other state. Once a thread is in a state of extinction, it no longer exists, so it is impossible to move to another state.
Typically, when an application runs, it calls the Stop method to terminate the thread if the current application is terminated with another external command. However, the most normal, most common way is because the thread in the operational state to complete its own task and "Die" to enter the extinction state, the completion of the task is implemented by the Run method




I. Multi-threaded concept


1. Processes and Threads
A program starts with at least one process, and at least one thread in a process.
2. Create a thread
A) write a class to inherit the thread, rewrite the Run method (), and write the thread to do in the subclass's run () method. Create such an object and call the start () method.
The program will open a new thread and run the Run () method on the new thread.
b). Write a class that implements the Runnable interface, and when the thread class object is created, the Runnable object is passed in the constructor, and the Runnable's run () method is called when the start () method is called.
3. Thread Alternation
In multi-threaded concurrency, the CPU can only work for one thread at a time, and multiple threads compete for CPU resources together.
Multi-thread concurrency does not improve efficiency if things in multiple threads are constantly consuming CPU.
If more than one thread is doing the same thing for a while, then multi-threaded concurrency can improve efficiency. This will increase the CPU utilization.

Note: The program we write usually only writes a main function when the program runs the virtual opportunity to execute the main function, does not perform other things, the main function of the code is from top to bottom, from left to right sequential execution, so this pattern is basically a single thread. In order to be able to run multiple threads, we can open a new thread under the main function, at this time how many new threads will run on how many new threads the Run method is running under the main function. There is no association between the various threads, each running their own, each thread at the same time grab the CPU, who rob to execute who, in order to let each thread orderly work, do not rob, we can use the sleep method to let the current thread sleep the specified time (in milliseconds), in this thread sleep time, this thread will let out the CPU, However, this method is not necessarily successful, some programs are very strong, do not let sleep, so the sleep method throws an exception. The switch of the thread is in the method unit. When a line thread method is executed, the CPU will provide the opportunity for all the threads to rob again, so if there is more than one method written in a thread, it is easy not to have another thread grab the CPU when all the methods of the thread are executed. In order to solve this problem we quoted the concept of lock. Put the method or code you want to execute in a synchronous code block. In this way, the thread will be able to execute its own code after the CPU has been robbed, and only when the code inside the synchronization code block is executed, the CPU can get the other threads to rob again. So we can use this method to ensure that the methods inside a thread are executed before the other threads execute, which reduces the security issue.
We can set the thread to be a background (daemon) thread through the Setdaemon (true) method, which must be set before threads are opened. If the thread of a program is left behind a background thread, the program will end automatically. In the main function of a program, as long as there is a non-background (daemon) thread running, the program will not end.
Two. Common APIs
1.sleep
Controls the current thread hibernation with an argument unit of milliseconds
Thread.Sleep (1000);Hibernate 1000 ms
2.setDaemon ()
Sets the current thread as the daemon thread, the daemon thread in the program does not run alone, and if all non-daemons in the program execute the end, the program exits directly.
Note To open the line setting on the thread.
3.join () which thread is to be merged into another thread to write which thread in the other thread. JOIN ();
At this point, wait for the other thread to finish running, and the thread to join will continue to run.
4.currentThread ()
Get the main thread
5.getName (), SetName ()
Get, set the name of the thread



Three. Synchronization of Threads
1. Thread Safety issues
Thread-safety issues can occur when multiple threads concurrently manipulate the same data.
2. Synchronizing code blocks
Use the keyword synchronized () {} to define a synchronization code block.
If a synchronization code block is encountered in multiple threads and the same lock flag is used, only 1 threads can enter, and the other waits until the thread executes the code in the synchronization code block before other threads can enter.
3. Synchronization method
Using the Synchronized keyword to decorate a method, the code in the entire method is synchronized
The lock flag used by the synchronization method is this
4. Deadlock
It is easy to create deadlocks when you call each other in multiple synchronized blocks of code.
In multi-threaded synchronization, if you need to use multiple locks, try to avoid nesting use, do not create deadlocks.

Four. Thread Communication
1. Wait
The lock flag. The wait () method can control the current thread wait, and any object has this method because the method is declared in the object class.
After wait (), the current thread yields the CPU resources until it is woken up by another thread.
2. Wake up
Lock Flag. The Notify () method wakes up a random thread that waits on a lock flag, and this method is also declared in the object class.
Notify () is a wake-up random one
Notifyall () Wakes all

Five. JDK5 Thread handling
1. Synchronization
Use the Reentrantlock Lock () method to start the synchronization, and the Unlock () method to end the synchronization.
2. Communication
Using the condition class's await () and signal () to wait and wake, the condition class object can be obtained through the lock class's newcondition ().

Thread Summary
1. Start the thread
In general, the Runnable form is used to create the thread class object, and a subclass of the Runnable interface is passed in the constructor, and when the start () method of the thread object is called, the Run () of runnable is called.
2. Synchronization of Threads
Generally use synchronous code block synchronized () {} Note that multiple threads that need to be synchronized must use the same lock flag
If all the code in a method needs to be synchronized, you can use the synchronization side, the lock flag used by the synchronization method is this

public class ThreadTest {


* The program will not end as long as there is a non-background (daemon) thread running.

public static void Main (string[] args) {run (); new MyThread (). Start (); MyThread MT = new MyThread (), Mt.setname ("MyThread"),//mt.setdaemon (TRUE);//set thread to Background thread mt.start (); int num = 0;while (true {if (num++>20) try{mt.join ();} catch (Exception e) {e.printstacktrace ();} Break System.out.println ("Main () in" + Thread.CurrentThread (). GetName ()); try{Thread.Sleep (100);} catch (Interruptedexception e) {e.printstacktrace ();}}} static void Run () {while (true) {System.out.println ("Run ()");}} Class MyThread extends Thread {public void run () {while (true) {System.out.println ("run ()" + thread.currentthread (). Get Name ()); try{Thread.Sleep (),} catch (Interruptedexception e) {e.printstacktrace ()}}} ---------------------------------------------------------------------------------public class TicketsSale1 {/** * Multi-threaded ticketing, simultaneous opening of four thread tickets * required to synchronize the multi-segment code to use the same lock * deadlock: */public static void Main (string[] args) {/* Four threads run four ticket procedures New Salethread (). Start () ; New Salethread (). Start (); New Salethread (). Start (); New Salethread (). Start (); */salethread1st = New SaleThread1 (), new Thread (ST), Start (), New Thread (ST), Start (); try{Thread.Sleep (10);} catch (Exception e) {e.printstacktrace ();} St.lock = "method"; new Thread (ST). Start (); new Thread (ST). Start ();}} Class SaleThread1 implements Runnable//extends Thread {int tickets = 100; String lock = "";p ublic Void Run () {if (Lock.equals ("method")) {while (true) {sale ()}} else {while (true) {synchronized (lock) {//each object can be used as a synchronous lock, the object has a flag bit (0, 1), Lock flag Sale (), if (tickets>0) {try{Thread.Sleep (100); }catch (Exception e) {e.printstacktrace ();} System.out.println (Thread.CurrentThread (). GetName () + ": Is Sale" + tickets--);}}}} Sync function, Sync function with Lock: this (ST) public synchronized Void sale () {synchronized (lock) {}if (tickets>0) {try{thread.sleep (100) ; }catch (Exception e) {e.printstacktrace ();} System.out.println (Thread.CurrentThread (). GetName () + ": sale () is Sale" + tickets--);}} ====================================================================================class SQL {String name; String Sex;boolEAN change = false;} Class DBA implements Runnable {private SQL Sql;public DBA (SQL sql) {this.sql = SQL;} public void Run () {int num = 0;while (true) {synchronized (SQL) {if (Sql.change) try{sql.wait ();} catch (Exception e) {E.print StackTrace ();} if (num==0) {sql.name = "Hukai"; sql.sex = "male";} else {sql.name = "Shaoyuejiao"; sql.sex = "female";} try {thread.sleep;} catch (Exception e) {e.printstacktrace ();} num = (num+1)%2;sql.change = True;sql.notify ();}}} Class Coder implements Runnable {private SQL sql;public coder (SQL sql) {this.sql = SQL;} public void Run () {while (true) {synchronized (SQL) {if (!sql.change) try{sql.wait ();} catch (Exception e) { E.printstacktrace (); }system.out.print ("name=" + Sql.name + ";"); /try {Thread.Sleep (ten);} catch (Exception e) {e.printstacktrace ();} System.out.println ("sex=" + sql.sex); sql.change = False;sql.notify ();}}} public class Sqlthread {/** * @param args */public static void main (string[] args) {SQL sql = new SQL ();D ba DBA = new DBA ( SQL); Coder Coder = new coder (SQL); new Thread (DBA). Start (); new Thread (coder). Start ();}} 


--------------------------------------------------------------------------------//Full, two remaining threads waiting, A fetch thread takes an element that wakes up one of the remaining threads//stored threads, and then it wakes up, wakes up another waiting thread, makes a mistake//solves the problem very simply, puts the condition of the thread waiting in a loop to judge// While actually the wait method allows audible spurious wakeup, it is best to put it in a loop//But like the above practice, the stored thread will go to wake up the stored thread, no need, very affect the efficiency of the program/*class MyArray {private int[] arr = new INT[10] ;p rivate String lock = "";p rivate int savepos = 0;private int getPos = 0;private int count = 0;public void add (int num) {s Ynchronized (Lock) {while (count==10) try{lock.wait ();} catch (Exception e) {e.printstacktrace ();} if (savepos==10) Savepos = 0;arr[savepos++] = num;count++;lock.notify ();//try{thread.sleep (n);} catch (Exception e) { E.printstacktrace (); }}}public int Get () {synchronized (lock) {try {while (count==0) try{lock.wait ();} catch (Exception e) {e.printstacktrace () ;} if (getpos==10) GetPos = 0;//try{thread.sleep (ten);} catch (Exception e) {e.printstacktrace ();} Count--;return arr[getpos++];} finally {lock.notify ();}}}} *///using 1.5 lock and condition to solve communication problems between storage and fetching class MyArray {private int[] arr = new INT[10];p rivate int savepos = 0;private int getPos = 0;private int count = 0;private lock lock = new Reentran Tlock ();p rivate Condition isfull = lock.newcondition ();p rivate Condition isEmpty = lock.newcondition ();p ublic void Add ( int num) throws Interruptedexception {try {lock.lock (); while (count==10) isfull.await (); if (savepos==10) Savepos = 0;arr[ savepos++] = Num;count++;isempty.signal ();} finally {Lock.unlock ();} Try{thread.sleep,} catch (Exception e) {e.printstacktrace ();}} public int get () throws Interruptedexception {try {lock.lock (), while (count==0) isempty.await (); if (getpos==10) GetPos = 0 ;//try{thread.sleep;} catch (Exception e) {e.printstacktrace ();} Count--;isfull.signal (); return arr[getpos++];} finally {Lock.unlock ();}}} public class Arraythread {/** * Write a multithreaded program that implements two lines Cheng elements, two threads take elements */static int num = 0;public static void Main (string[] args) {f Inal MyArray Marr = new MyArray (), New Thread (new Runnable () {public void run () {for (int i=0; i<30; i++) {try {Marr.add ( Num++);} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}}). Start (); New Thread (New Runnable () {public void run () {for (int i=0; i<30; i++) try {System.out.println (Marr.get ());} Cat CH (interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}). Start (); New Thread (New Runnable () {public void run () {for (int i=0; i<30; i++) {try {marr.add (num++);} catch (Interrupte Dexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}}). Start (); New Thread (New Runnable () {public void run () {for (int i=0; i<30; i++) try {System.out.println (Marr.get ());} Cat CH (interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}). Start ();}}


Java Multi-Threading understanding

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.