4. Multi-thread synchronization

Source: Internet
Author: User
Tags semaphore ticket

First, synchronization: synchronized

Sync Concurrency Multiple threads access the same resource to ensure resource security ----> Thread safety

    • Sync Block:

Synchronized (Reference type | this | class. Class) {

}

    • Synchronization method: public static synchronized void ...---->web12306

web12306 Code implementation:

Package com.cust.syn;/** * Description: Synchronizing concurrent multiple threads accessing the same resource * synchronized thread safety * @author Cookie */public class SynDemo01 {public S tatic void Main (string[] args) {//Real role Web12306 w = new Web12306 ();//three agent roles thread T1 = new Thread (W, "passer-by"); Thread t2 = new Thread (W, "Ox B"); thread t3 = new Thread (W, "Siege Lion"); T1.start (); T2.start (); T3.start ();}}    Class Web12306 implements Runnable {Private Boolean flag = true; int num = ten; @Overridepublic void Run () {while (flag) {TEST5 ();}} The lock resource is incorrect---> thread unsafe rate Comparison high public void Test5 () {//a B csynchronized ((Integer) num) {//Lock if (num <= 0) {flag = Fals e;//thread end return;} A b ctry {thread.sleep ($);//runnable cannot throw an exception outside} catch (Interruptedexception e) {e.printstacktrace ();} System.out.println (Thread.CurrentThread (). GetName () + "grabbed the first" + num--+ "Ticket");}} A b = 0 c = -1//lock range is incorrect---> thread unsafe rate Comparison high public void test4 () {//a B csynchronized (this) {//Lock the object that calls this method is Web12306if ( Num <=0) {flag = false;//thread end return;}} A b ctry {thread.sleep ($);//runnable cannot throw an exception outside} catch(Interruptedexception e) {E.printstacktrace ();} System.out.println (Thread.CurrentThread (). GetName () + "grabbed the first" + num--+ "ticket"); A b = 0 c = -1//lock sync block---> Line shuo full speed low public void test3 () {synchronized (this) {///Lock the object that called this method is web12306if (num <=0 {flag = false;//thread end return;} try {thread.sleep;//runnable cannot throw an exception outside} catch (Interruptedexception e) {e.printstacktrace ();} System.out.println (Thread.CurrentThread (). GetName () + "grabbed the first" + num--+ "Ticket");}} Locking Method---> Line shuo Full speed low public synchronized void Test2 () {if (num <=0) {flag = false;//thread end return;} try {thread.sleep;//runnable cannot throw an exception outside} catch (Interruptedexception e) {e.printstacktrace ();} System.out.println (Thread.CurrentThread (). GetName () + "grabbed the first" + num--+ "ticket"); Concurrency does not handle----> thread restless full rate lower public void test1 () {if (num <=0) {flag = false;//thread end return;} try {thread.sleep;//runnable cannot throw an exception outside} catch (Interruptedexception e) {e.printstacktrace ();} System.out.println (Thread.CurrentThread (). GetName () + "grabbed the first" + num--+ "Ticket");}}

Second, the single case mode 

Lazy and a hungry man-style

Package com.cust.syn;/** * Singleton mode * GC JVM trash Runtime * Lazy type: Double checking double check * 1. Constructor privatization * 2. Declaring a private static variable *  3. Create a common static method, access the variable, and make sure that there is a variable * a hungry man: * * @author Cookie */public class Singletondemo {}/** * lazy: Double checking double-check * 1. Constructor privatization * 2. Declare a private static variable * 3. Create a common static method, access the variable, and make sure that there is a variable * @author cookie */class jvm{private static JVM jvm;private JVM () {}public static JVM getinstance () {if (null = = JVM) {//Increase efficiency, do not enter the method if the object already exists synchronized (Jvm.class) {// Static method cannot call Thisif (NULL==JVM) {//If not present, create object security JVM = new JVM ();}}} return JVM;}} /** * A hungry man: * 1. Constructor privatization * 2. Declare a private static variable and instantiate the variable at the same time * 3. Create a common static method, Access variable * @author cookie */class jvm2{private static JV M2 JVM = new JVM2 ();p rivate JVM2 () {}public static JVM2 getinstance () {///Do not use this method, the variable may be initialized to the return JVM;}} /** * class loaded during use, Delay load time (MYJVM) a hungry man recommended * @author cookie */class jvm3{private static class Myjvm{private static JVM3 JVM = new JVM3 ();} Private JVM3 () {}public static JVM3 getinstance () {//does not use this method and does not load Myjvmreturn MYJVM.JVM;}}

Three, deadlock: Too much synchronization is prone to deadlock

/** * Description: Deadlock: Too much synchronization easy to cause deadlock * @author Cookie */public class SynDemo03 {public static void main (string[] args) {Object g = n EW object (); object m = new Object (); Test T1 = new test (G,M); Test2 t2 = new Test2 (g,m); Thread proxy = new thread (t1); Thread Proxy2 = new Thread (t2);p Roxy.start ();p Roxy2.start ();}} Class Test implements Runnable{object Goods;object money;public Test (object goods, object money) {this.goods = Goods;this. Money = money;} @Overridepublic void Run () {test ();} public void Test () {synchronized (goods) {try {Thread.Sleep ($)} catch (Interruptedexception e) {e.printstacktrace ();} Synchronized (Money) {}}system.out.println ("Pay by Hand");}} Class Test2 implements Runnable{object Goods;object money;public Test2 (object goods, object money) {this.goods = Goods;thi S.money = money;} @Overridepublic void Run () {test ();} public void Test () {synchronized (money) {try {Thread.Sleep ($)} catch (Interruptedexception e) {e.printstacktrace ();} Synchronized (goods) {}}system.out.println ("hand Delivery");}}

Iv. Resolve deadlocks: Producer Consumer semaphore method

Package com.cust.pro;/** * A scene common resource producer consumer mode Semaphore Method object:wait () Release lock wait Sleep () do not release lock * Notify ()/notifyall () wake-up wait * * @au Thor Cookie */class Movie {private String pic;//semaphore//semaphore//Flag---->t producer production, consumer wait, production finished after production, wake-up consumer//flag----&GT;F Consumer  Fee, producer waits, consumer consumer finishes, wake producer private Boolean flag = True;public synchronized void Play (String pic) {if (!flag) {//consumer consumer producer waits for try {this.wait ();} catch (Interruptedexception e) {e.printstacktrace ();}} try {thread.sleep;} catch (Interruptedexception E1) {e1.printstacktrace ();} Production end this.pic = pic; System.out.println ("produced:" + pic);//wake-up consumer, this.notifyall ();//producer End this.flag = false;} public synchronized Void Watch () {if (flag) {//producer production, consumer waits for try {this.wait ();} catch (Interruptedexception e) {E.printstack Trace ();}} Consumer consumption try {thread.sleep ($);} catch (Interruptedexception e) {e.printstacktrace ();} Consumption completed System.out.println ("consumption:" + this.pic);//wake-up producer This.notify ();//consumer waits for this.flag = true;}} Class Player implements Runnable{private Movie m;public Player (Movie m) {this.m = m;} @Overridepublic void Run () {for (int i = 0; i <; i++) {if (0==i%2) {M.play ("left Tsing Lung");} Else{m.play ("Right white Tiger");}}} Class Watcher implements Runnable{private movie M;public watcher (Movie m) {this.m = m;} @Overridepublic void Run () {for (int i = 0; i <; i++) {M.watch ();}}} public class App {public static void main (string[] args) {//common resource movie m = new Movie ();//multithreaded Player P = new player (m); Watcher W = new Watcher (m); new Thread (P). Start (); new Thread (W). Start ();}}

  

4. Multi-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.