Synchronization of Threads
When multiple threads are using resources that are synchronized in the same object, they are used in the order of "first served".
For example: Now there is only one computer, now there are two people A and B want to play games, a person C want to write code, a person D want to listen to music. At this time a, B, C three people to rob this computer, who first grabbed who use, after the end of two people in the next Rob, who Rob who use. D is not necessary, in the other three people any one is in use, can play music to him, so you can see the game and Write code function (method) is to have "first served" order, and listen to music this function does not need. So the way to play and write code is to be synced, and listening to music doesn't need to be synchronized.
Synchronization using keyword synchronized implementation
Synchronization method:[access modifier] Synchronized return value type method name () {}
Sync Block:synchronized (object) {//code block}
The synchronization block is the same as the code block mentioned earlier, except that the code is synchronized. The synchronized parts are also executed in the order of "first served"
In the development process, you should try to narrow the scope of the synchronization code, because the execution of multiple threads should be executed sequentially, which will greatly reduce the efficiency of the program run
The following instance code creates a computer class that contains a non-synchronous method Listenmusic, a non-synchronous method printer with a synchronization block, and two synchronization methods PlayGame and coding.
Seven thread classes Threada, THREADB, THREADC, Threadd, Threade, THREADF, THREADG, where non-synchronous methods are performed in Threada and threadb Listenmusic ; THREADC and Threadd both performed synchronous methods Playgame;threade The synchronous method was performed in CODING;THREADF THREADG all performed a non-synchronous method with synchronized blocks printer;
Five test classes Testab, TESTBC, Testcd, Testde, Testef, TESTFG; test the two threads of the object based on the last two letters of the class name of the test class, for example Testab test Threada and THREADB
Instance:package thread.synchronize;/** * create Computer class * which contains synchronous methods, non-synchronous methods, and non-synchronous methods that contain synchronization blocks * @author Genius Federation - Yukun */public class Computer {/** * Non-synchronous methods ; function: Listen to music * @param threadtag: Thread tag that identifies which thread is executing this method */public void listenmusic ( String threadtag) {system.out.println (threadtag + "-Listen to music start") try {// This sleeps for 1 seconds to simulate the time Thread.Sleep (1000) spent writing code;} catch (interruptedexception e) {e.printstacktrace ();} System.out.println (threadtag + "-Listen to music End");} /** * non-synchronous method with synchronous block; function: print material * @param threadtag: Thread tag that identifies which thread is executing this method */public void printer (String threadtag) {system.out.println (threadtag + "-Preparation material start"); try {//here sleeps for 1 seconds to simulate the time Thread.Sleep (1000) of preparing material consumption;} catch (interruptedexception e) {e.printstacktrace ();} System.out.println (threadtag + "-Prepare material End");//sync block: Gets the current object's lock synchronized (this) {SysTem.out.println (threadtag + "-Print material start") try {//here to sleep for 1 seconds is to simulate the time spent on printing material thread.sleep (1000);} catch (interruptedexception e) {e.printstacktrace ();} System.out.println (threadtag + "-Print material End");}} /** * synchronization method; function: Play games * @param threadtag: Thread tag that identifies which thread is executing this method */public Synchronized void playgame (String threadtag) {system.out.println (threadTag + "- Play the game start "); try {//here sleeps for 3 seconds to simulate the time spent playing the game Thread.Sleep (3000);} catch (interruptedexception e) {e.printstacktrace ();} System.out.println (threadtag + "-Play Game Over");} /** * synchronous method; function: Write code * @param threadtag: Thread tag that identifies which thread is executing this method */public Synchronized void coding (String threadtag) {system.out.println (threadTag + "- Write code to start "); try {//here sleeps for 3 seconds to simulate the time spent thread.sleep writing code (3000);} catch (interruptedexception e) {e.printstacktrace ();} System.out.println (Threadtag + "-Write Code End");}} package thread.synchronize;/** * create Threada class * to perform a non-synchronous method in computer object listenmusic * @author Genius Alliance - Yukun */public class threada extends thread {/* * declaring member variables pc * The purpose is to use an externally passed computer object in the Run method * the local variable in the constructor method cannot be used in the Run method LOCALPC * So here we declare a member variable that the PC is used to receive externally incoming objects * so since the Run method, you can use the external incoming object through the member variable PC */private computer pc;/* * the LOCALPC here will receive an object of the externally passed-in computer type * and pass it to the member variable pc */public Threada (COMPUTER LOCALPC)  {PC = LOCALPC;} @Overridepublic void run () {//the ability to listen to music using a PC, i.e. using a PC to invoke the Listenmusic method Pc.listenmusic ("Threada");}} package thread.synchronize;/** * create THREADB class: Role and code with threada * @author Genius Alliance - Yukun */public class ThreadB extends Thread {private Computer pc; PUBLIC THREADB (COMPUTER LOCALPC) {PC = LOCALPC;} @Overridepublic void run () {pc.listenmusic ("threadb");}} package thread.synchronize;/** * Create a test class testab * to test multiple threads simultaneously calling the same non-synchronous method of the same object * The result will be multiple threads simultaneously executing the asynchronous method * @author Genius Federation - Yukun */public class Testab {public static void main (String[] args) {/** * to ensure that only one computer (that is, the same object) is accessible to multiple threads * only one computer object is created here as an argument passed to each thread */computer pc = new computer ();//threada and threadb have performed a PC's asynchronous method listenmusicthreada ta = new threada (PC); THREADB  TB = NEW  THREADB (PC);//Start Thread ta and Tbta.start (); Tb.start ();}} Running result: threada-listen to music start threadb-listen to music start threadb-listen to music end threada-listen to music end
package thread.synchronize;/** * Create THREADC Class: Code basic and Threada same * @author Genius Federation - Yukun */public class ThreadC extends Thread {private Computer pc; PUBLIC THREADC (COMPUTER LOCALPC)  {PC = LOCALPC;} @Overridepublic void run () {//call the PC's synchronization method Playgamepc.playgame ("THREADC");}} package thread.synchronize;/** * creates a test class testbc * used to test two threads for simultaneous calls to the same object's non-synchronous method and synchronous method * The result is that two threads executing the unsynchronized method and the synchronous method can execute simultaneously without affecting * @author Genius Federation - Yukun */public Class testbc {public static void main (String[] args) {/** * to ensure that only one computer (that is, the same object) is accessible to multiple threads * only one computer object is created here as an argument passed to each thread */computer pc = new computer ();//threadb performs a non-synchronous method of the PC LISTENMUSICTHREADB  TB  = NEW  THREADB (PC);//THREADC performs the synchronization method of the PC playgamethreadc tc = NEW  THREADC (PC); Tb.start (); Tc.start ();}} Running result: threadc-play the game start threadb-listen to music start threadb-listen to music end threadc-play game end
package thread.synchronize;/** * Create Threadd Class: Code and functionality with threadc * @author Genius Federation - Yukun */public class ThreadD extends Thread {private Computer pc; Public threadd (COMPUTER LOCALPC)  {PC = LOCALPC;} @Overridepublic void run () {//call the PC's synchronization method Playgamepc.playgame ("Threadd");}} package thread.synchronize;/** * Create a test class testcd * is used to test multiple threads simultaneously calling the same synchronization method of the same object * The result is that one line of enters upgradeable gets the lock of the object after execution, the second thread can execute * @author Genius Federation - Yukun */public class testcd {public static void main (String[] args) {/* * * to ensure that only one computer (that is, the same object) is accessible to multiple threads * Therefore, only one computer object is created here as an argument passed to each thread */Computer pc = new computer ();//THREADC and Threadd all perform the synchronization method of the PC PLAYGAMETHREADC  TC  = NEW  THREADC (PC); threadd td = new Threadd (PC);//Start Thread TC and Tdtc.start (); Td.start ();}} Running result: threadc-Play game start threadc-play game end threadd-play game start threadd-play game end
package thread.synchronize;/** * create Threade class * @author Genius Alliance - Yukun * /public class threade extends thread {private computer pc;public Threade (COMPUTER LOCALPC)  {PC = LOCALPC;} @Overridepublic void run () {//call the PC's synchronization method codingpc.coding ("Threade");}} package thread.synchronize;/** * Create a test class testde * to test different synchronization methods for multiple threads calling the same object at the same time * The result is a line of enters upgradeable. Once the lock for the object is executed, the second thread can execute * @author Genius Federation - Yukun */public class testde {public static void main (String[] args) {/* * * to ensure that only one computer (that is, the same object) is accessible to multiple threads * Therefore, only one computer object is created here as an argument passed to each thread */Computer pc = new computer ();//threadd performed the synchronization method of the PC playgamethreadd td = New threadd (PC), synchronous method of PC is performed in//threade codingthreade te = new tHreade (PC); Td.start (); Te.start ();}} Run Result: threadd-Play game start threadd-play game end threade-write code start threade-write code end
package thread.synchronize;/** * create THREADF class * @author Genius Alliance - Yukun * /public class threadf extends thread {private computer pc;public THREADF (COMPUTER LOCALPC)  {PC = LOCALPC;} @Overridepublic void run () {//call the PC with a synchronous block method Printerpc.printer ("THREADF");}} package thread.synchronize;/** * Creating a test class testef * a synchronous method that tests multiple threads to invoke the same object at the same time and a non-synchronous method that contains synchronous blocks * results will be synchronized parts have successively, non-synchronized portions of code executed simultaneously * @author Genius Federation - Yukun */public Class testef {public static void main (String[] args) {/** * to ensure that only one computer (that is, the same object) is accessible to multiple threads * only one computer object is created here as an argument passed to each thread */computer pc = new computer (); The synchronization method of the PC is performed in//threade codingthreade te = new threade (PC);//THREADF executes a PC's asynchronous method with synchronized blocks Printerthreadf tf = neW  THREADF (PC); Te.start (); Tf.start ();}} Run Result: threadf-prepare material start threade-Writing code start threadf-prepare material end threade-Write code end threadf-print material start threadf-print material end
package thread.synchronize;/** * create THREADG class * @author Genius Alliance - Yukun * /public class threadg extends thread {private computer pc;public THREADG (COMPUTER LOCALPC)  {PC = LOCALPC;} @Overridepublic void run () {//call the PC with a synchronous block method Printerpc.printer ("THREADG");}} package thread.synchronize;/** * Creating a test class testfg * is used to test multiple threads simultaneously calling the same object in a non-synchronous method that contains a synchronous block * results will be synchronized parts have successively, non-synchronized portions of code executed simultaneously * @author Genius Federation - Yukun */public class testfg {public static void main (String[] args) {/* * * to ensure that only one computer (that is, the same object) is accessible to multiple threads * Therefore, only one computer object is created here as an argument passed to each thread */Computer pc = new computer ();//THREADF and THREADG all perform the asynchronous method of the PC with synchronous block PRINTERTHREADF  TF  = NEW  THREADF (PC); Threadg tg = new threadG (PC); Tf.start (); Tg.start ();}} Running result: threadf-preparation material start threadg-preparation material start threadg-prepare material end threadg-Print material start threadf-prepare material end threadg-print material end threadf-print material start threadf-print material end
the Wait method and the Notify method/notifyall method
Wait ([Int][,int]); method in the object class, using object o in thread A to call the wait method;
If there is no time parameter passed in, it will not recover until the Notify/notifyall of object o is called elsewhere;
If you pass in a long type of time parameter, the specified time after the end of the automatic recovery
And thread A must first obtain the lock of object o, otherwise an exception will occur.
Instance:package thread.wait;/*** creating Waitdemo class * for testing wait, notify, Notifyall methods * @author Genius Federation - Yukun */public class waitdemo {public static void main (String[] args) {/* * create a unique object here onlyobject * is used to pass to the following three threads to ensure that three threads are using the same object */ Object onlyobject = new object ();/* * create three thread objects Ta, TB, tc * Onlyobject will be assigned to variables in the constructor method of each thread localobject * equivalent to Localobject = onlyobject; */threada ta = new threada (Onlyobject); THREADB TB = NEW THREADB (Onlyobject); THREADC TC = NEW THREADC (onlyobject);//Start thread Ta and Tbta.start first (); Tb.start (); try {/* * This executes thread.sleep (100); The main thread sleeps 100 milliseconds * 100 milliseconds before Tc.start () is executed; start thread tc * The purpose is to ensure that the wait method in thread TA and TB is executed first, blocking the thread TA and tb * then executing the Notify () method in the thread TC is the wake operation * Otherwise if the wake operation is performed before the blocking operation, will not see the effect of Awakening */thread.sleep (100);} catch (interruptedexception e) {e.printstacktrace ();} Start thread Tctc.start ();}} /*** create Threada class * to perform the wait method; blocking operations * @author Genius Federation - Yukun */class threada extends thread {/* * declares member variables obj * The purpose is to use externally passed object objects in the Run method * However, the local variable in the constructor method cannot be used in the Run method localobject * so this declares a member variable, obj, to receive the externally passed-in object * so since the Run method, You can use an externally-passed object through the member variable, obj */private Object obj;/* * the localobject here will receive an object of the type that was passed in * assigns it to the member variable Obj */public threada (object localobject) {//to the member variable Objthis.obj = localobject;} @Overridepublic void run () {system.out.println ("threada--execution start");/* * calls the Wait method, You must use a synchronous way to get the lock on the Wait method object to be called * otherwise the illegalmonitorstateexception exception will occur * in this case, It is used here that obj calls Wait (obj.wait ()) * so the synchronization should also be obj (synchronized (obj) ) */synchronized (obj) {try {system.out.println ("threada--blocked");/* * Call Object obj WThe Ait method, which is blocking the thread that will execute this code * This example is the thread TA that executes the code here, so the thread ta */obj.wait () is blocked; System.out.println ("threada--is Awakened");} catch (interruptedexception e) {e.printstacktrace ();}} System.out.println ("threada--execution End");}} /*** creates the Threadb class * to execute the wait method, and the blocking operation * the same code as Threada, no more one by one write comments * @author Genius Alliance - Yukun */CLASS THREADB EXTENDS THREAD {PRIVATE OBJECT OBJ;PUBLIC THREADB ( Object localobject) {this.obj = localobject;} @Overridepublic void run () {synchronized (obj) {system.out.println ("threadb--execution start"); synchronized (obj) {try {system.out.println ("threadb--is blocked");/* * execute obj.wait (), The blocking will be the thread that executes this code * in this case the code is executed here is the thread TB, so being blocked is thread tb */obj.wait (); System.out.println ("threadb--is Awakened");} catch (interruptedexception e) {e.printstacktrace ();}} System.out.println ("threadb--execution End");}}} /*** create THREADC class * to execute Notify method; Wake Operation * @author Genius Alliance - Yukun */class threadc extends thread {private object obj; PUBLIC THREADC (Object localobject) {this.obj = localobject;} @Overridepublic void run () {/* * Call the Notify method, you must obtain the lock that invokes the Notify method object in a synchronous manner * Otherwise, the illegalmonitorstateexception exception will occur * in this case, the obj call Notify (Obj.notify ()) is used here * So the synchronization should also be obj (synchronized (obj) ) */synchronized (obj) {system.out.println (" threadc--wakes the thread that was first blocked by the Obj object ");/* * executes Obj.notify (), wakes the first thread that was blocked by obj * if execution obj.notifyall (); All threads that are blocked by obj will be awakened */obj.notify ();}}} Run Result: threada--execution start threadb--execution start threadb--blocked threada--blocked threadc--wake first thread blocked by obj object threadb--Wake threadb--execution End
Summary: Thread synchronization is to protect the security of the data in the process of multithreading, but this greatly affects the efficiency of the software execution, so in the process of using synchronization, the synchronization scope should be reduced as much as possible, thus reducing the effect of synchronization on performance.
This article from the "Genius Union Education Official Blog" blog, reproduced please contact the author!
I genius official Free tutorial 40: Java Essentials thread synchronization