I genius official Free tutorial 40: Java Essentials thread synchronization

Source: Internet
Author: User

Synchronization of ThreadsWhen 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
Example: Package thread.synchronize;/** * Create Computer class * which contains synchronous methods, non-synchronous methods and unsynchronized methods with synchronized blocks * @author Genius Federation-Yukun */public class Computer { /** * Non-synchronous method; 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 {//Hibernate here for 1 seconds is to simulate the time spent writing code thread.sleep ()} 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 + "-Prep material start"); try {//Hibernate here for 1 seconds is to simulate the time to prepare material consumption thread.sleep ()} 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 {//Hibernate here for 1 seconds is to simulate the time that the print material consumes thread.sleep (1000);} catch (Interruptedexception e) {e.printstacktrace ();} System.out.println (Threadtag + "-Print material End");}} /** * synchronization method; function: Play game * @param threadtag: Thread tag, which identifies which thread is executing this method */public Synchronized void PlayGame (String threadtag) {System.out.println (Threadtag + "-Play Game Start"), try {//here sleeps 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");} /** * synchronization method; function: Write code * @param threadtag: Thread tag that identifies which thread is executing this method */public synchronized void coding (String threadtag) {SYSTEM.O Ut.println (Threadtag + "-Write code Start"); try {//Hibernate here for 3 seconds is to simulate the time spent writing code thread.sleep ();} catch (Interruptedexception e) { E.printstacktrace ();} System.out.println (Threadtag + "-Write code End");}} Package thread.synchronize;/** * Create Threada class * for performing non-synchronous methods in computer objects Listenmusic * @author Genius Federation-Yukun */public class Threada Extends Thread {/* * DECLARE member variable PC * The purpose is to use an externally passed computer object in the Run method * But the local variable in the constructor method cannot be used in the Run method LOCALPC * So here is a member variable that the PC uses to receive externally incoming objects * So since the Run method, you can use a member variable PC can be used externally passed in object */private computer pc;/* * The LOCALPC here receives an externally-passed object of type computer and passes it to the member variable PC */public Threada (computer localpc) {pc = LOCALPC;} @Overridepublic void Run () {///use PC to complete listening music, i.e. use PC to call Listenmusic method Pc.listeNmusic ("Threada");}} Package thread.synchronize;/** * Create THREADB class: function and code with THREADA * @author Genius Federation-Yukun */public class Threadb extends thread {Priva Te computer pc;public threadb (computer localpc) {pc = LOCALPC;} @Overridepublic void Run () {pc.listenmusic ("threadb");}}  Package thread.synchronize;/** * Create 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 an unsynchronized 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 * So just create a computer object here as an argument to each Thread */computer PC = new computer (),//threada and threadb both perform 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;/** * Create Test class TESTBC * To test two threads simultaneously calling non-synchronous methods and synchronous methods of the same object * The result is that two threads executing the unsynchronized method and the synchronous method can execute concurrently, without affecting each other * @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 * So just create a The computer object is passed as an argument to each thread */computer PC = new computer ();//threadb performs a non-synchronous method of the PC listenmusicthreadb TB = new threadb (PC);//thr EADC performed the synchronization method of the PC PLAYGAMETHREADC TC = new THREADC (PC); Tb.start (); Tc.start ();}} Running results: threadc-play the game start threadb-listen to music start threadb-listen to the end of the music threadc-play the 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 Test class TESTCD * To test multiple threads simultaneously calling the same synchronous method of the same object * result is a line enters upgradeable the lock that gets the object is executed, the second thread can execute * @author Genius Federation-Zhao */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 * So only one computer is created here The object is passed as an argument to each thread */computer PC = new computer (), and both//THREADC and Threadd perform the PC synchronization method PLAYGAMETHREADC TC = new THREADC (PC); Threadd td = New Threadd (PC);//Start Thread TC and Tdtc.start (); Td.start ();}} Run 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 Federation-Yukun */public class Threade Exten DS 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 Test class TESTDE * To test different synchronization methods for multiple threads calling the same object at the same time * result is also a certain line of enters upgradeable to get the lock of the object after execution, 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 * So only one comput is created here The ER object is passed as an argument to each thread */computer PC = new computer ();//threadd performs a synchronous method of the PC Playgamethreadd TD = New Threadd (PC);//threade performs a PC Synchronization method 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 Federation-Yukun */public class THREADF Exten DS 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;/** * Create Test class TESTEF * To test multiple threads simultaneously calling synchronous methods of the same object and non-synchronous methods with synchronization blocks * The result will be the synchronized part has successively, the asynchronous part code executes 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 * So just create a The computer object is passed as an argument to each thread */computer PC = new computer (), the synchronization method of the PC is performed in//threade codingthreade te = new Threade (PC);//THREADF PRINTERTHREADF tf = new THREADF (PC), Te.start (); Tf.start ();}, the asynchronous method of the PC 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 Federation-Yukun */public class THREADG extends thread {private computer PC ;p ublic THREADG (computer localpc) {pc = LOCALPC;} @Overridepublic void Run () {//Call the PC with a synchronous block method Printerpc.printer ("THREADG");}} Package thread.synchronize;/** * Create Test class TESTFG * To test multiple threads simultaneously calling the same object in the same asynchronous method that contains the synchronization block * The result will be the synchronized part has successively, the non-synchronous part code executes 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 * Only one computer object is created here as an argument passed to each thread */computer  pc = new  computer ();// Both the THREADF and the THREADG perform a non-synchronous method of the PC with synchronized blocks 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 methodwait ([Int][,int]); Methods in the object class, using object o in thread A to call the wait method; blocking threads A;
if there is no time parameter passed in, it will not recover until the Notify/notifyall of object o is called elsewhere.
If a long type of time parameter is passed, automatically resumes after the specified time
And thread A must first obtain the lock of object o, otherwise an exception will occur.
Example: Package thread.wait;/*** Create Waitdemo class * For testing wait, notify, Notifyall methods * @author Genius Federation-Yukun */public class Waitdemo {public St atic void Main (string[] args) {/* * Creates a unique object objects here Onlyobject * is used to pass to the following three threads to ensure that three threads are using the same object */object Onlyobject = n EW object ();/* * Create three thread objects Ta, TB, TC * Onlyobject will be assigned to variables in the constructor method of each thread Localobject * equals localobject = Onlyobject; */threada ta = new Threada (onlyobject); THREADB TB = new THREADB (onlyobject); THREADC TC = new THREADC (onlyobject);//Start Thread ta and Tbta.start (); Tb.start (); try {/* * here executes Thread.Sleep (100); it will be the main thread hibernate 100 milliseconds * The Tc.start () is not executed until 100 milliseconds, and the start thread TC * is designed to ensure that the wait method in thread TA and TB is executed first, blocking thread ta and TB * and then notify () method in thread TC is wake operation * Otherwise if Wake operation is performed first, Then the blocking operation will not see the effect of Wake */thread.sleep (100);} catch (Interruptedexception e) {e.printstacktrace ();} Start thread Tctc.start ();}} /*** Create Threada class * Used to execute the wait method; Blocking operation * @author Genius Federation-Yukun */class Threada extends Thread {/* * DECLARE member Variable obj * Purpose is because the Run method requires the use of externally passed in Object Objects * But the Run method cannot use local variables in the constructor method Localobject * So declare here a member variable obj is used to receive an externally passed in object * So since the run method, it is possible to use the member variable, obj, by using the externally passedLike the */private object obj;/* * Here Localobject will receive an externally passed objects of type * and pass it to the member variable obj */public Threada (object localobject) {//Assignment Value to member variable objthis.obj = localobject;} @Overridepublic void Run () {System.out.println ("threada--execution Start");/* * When you call the Wait method, you must obtain a lock that calls the Wait method object in a synchronous manner * Otherwise, the illegalmonitorstateexception exception will occur * In this case, the obj call Wait (obj.wait ()) * is used here, so the synchronization should also be obj (synchronized (obj)) */ Synchronized (obj) {try {System.out.println ("threada--is blocked");/* * Call Object obj's Wait method, which will block the thread executing this code * This example is the thread TA that executes the code here, So the block is the thread Ta */obj.wait (); System.out.println ("threada--is Awakened");} catch (Interruptedexception e) {e.printstacktrace ();}} System.out.println ("threada--execution End");}} /*** Create THREADB class * To execute the wait method; The block operation * where the code and Threada are the same, no more one by one write comments * @author Genius Federation-Yukun */class THREADB extends Thread {private Obje CT 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"),/* * executes obj.wait (), blocking will be the thread executing this code * In this case, it is the thread TB that executes this code, 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 perform notify method; Wake Operation * @author Genius Federation-Yukun */class THREADC extends Thread {private Object obj;public threadc (obj ECT localobject) {this.obj = Localobject;} When you call the Notify method @Overridepublic void Run () {/* *, you must get the lock that calls the Notify method object synchronously by using synchronous methods * Otherwise, the illegalmonitorstateexception exception will appear * in this case, This is used by the obj call Notify (Obj.notify ()) * 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 is blocked by obj * If execution obj.notifyall (), and all threads that are blocked by obj are woken */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.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

I genius official Free tutorial 40: Java Essentials thread synchronization

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.