JAVA04 thread synchronization Problem resolution--thread lock (synchronous lock, mutual exclusion lock)

Source: Internet
Author: User

Directory

[TOC]

Written in the front:

May be wrong, please criticize me

One, thread switching

In Java, if you want to implement thread switching between threads, you need to use Thread.yield () in the thread to yield CPU time.

Second, the line lock (also known as synchronous lock, mutual exclusion lock)

The thread lock can effectively reduce the synchronization range while ensuring the concurrency efficiency as much as possible.

2.1 Using the Synchronized keyword to lock a method

Locking for the entire threading process ( severe impact on efficiency, infrequently used )

2.1.1 Syntax
publicsynchronizedvoidtest(){    }
2.1.2 Case
Package Com.javase.thread;import javax.management.RuntimeErrorException;/*** This class mainly tells the Sychronized keyword, after adding the Synchronized keyword to the method, when the thread calls this method, it is equivalent to locking the method.* Then other threads cannot call this method (in a blocking state) *  * @authorGupan * */ Public classthreadsyncsychronized { Public Static void Main(string[] args) {FinalTable2 table =New Table2(); Thread T1 =NewThread () { Public void Run() { while(true) {Try{intBean = table.Getbean(); Thread.yield();//thread switch statement, yielding CPU timeSystem. out.println(GetName() +","+ table.Getbean()); }Catch(Runtimeerrorexception e) {System. out.println(GetName() +","+ e); Break;                }                                    }            }        }; Thread t2 =NewThread () { Public void Run() { while(true) {Try{intBean = table.Getbean(); Thread.yield();//thread switch statement, yielding CPU timeSystem. out.println(GetName() +","+ table.Getbean()); }Catch(Runtimeerrorexception e) {System. out.println(GetName() +","+ e); Break;        }                }            }        }; T2.Start(); T1.Start(); }}classtable2{//There are 20 dollars on the table.    Private intBeans = -; Public synchronized int Getbean()throwsruntimeerrorexception{if( This.Beans==1) {Throw NewRuntimeerrorexception (NULL,"The landlord's house is surplus."); } Thread.yield();//thread switch statement, yielding CPU time        return  This.Beans--; }}
2.2 Use the Synchronize keyword on a part of a thread method locking (how to synchronize a block) 2.2.1 syntax
// 注意这里是this,可以写new Object(),但是这样起不到加锁的效果// 也就是说,要实现加锁的效果,需要保证是对同一个对象(也就是保证synchronized后面所跟对象是同一个)加锁synchronized(this){    ···    // 加锁语句}
2.2.2 Case
Package Com.javase.thread;/*** This class mainly demonstrates a small range of use locks. Increase concurrency efficiency as much as possible * * Synchronized (this) { *      ···*//Locking Statement * } *  * @authorThink * */ Public classThreadsynclock { Public Static void Main(string[] args) {FinalShop shop =New  Shop(); Thread T1 =NewThread () { Public void Run() {Shop.buy();                }        }; Thread t2 =NewThread () { Public void Run() {Shop.buy();                }        }; T1.Start(); T2.Start(); }}classshop{ Public void buy() {Thread t = thread.CurrentThread();Try{System. out.println(T.GetName() +"I'm picking clothes."); Thread.Sleep( +);//need to pass in the object to which the current method belongs, so pass this here            synchronized( This) {System. out.println(T.GetName() +"trying clothes."); Thread.Sleep( +); } System. out.println(T.GetName() +"Checkout and Departure"); Thread.Sleep( +); }Catch(Exception e) {//Todo:handle exceptionE.Printstacktrace(); }    }}
2.3 Static method plus lock

If you add a synchronized keyword to a static method, the entire method must be a mutex because there is only one copy of the static method

Package Com.javase.thread;import Com.javase.string.Object;/*** Synchronization of static methods* When a static method is synchronized modified, then this method is the synchronous method, due to the static method dependent class,* Global is a copy, so the synchronous static method must have the synchronization effect, is not related to the object *  * @authorGupan * */ Public classthreadsyncstatic { Public Static void Main(string[] args) {Thread T1 =NewThread () { Public void Run() {Foo.Dosome();        }        }; Thread t2 =NewThread () { Public void Run() {Foo.Dosome();        }        }; T1.Start(); T2.Start(); }}classfoo{ Public Static synchronized void Dosome() {Try{Thread T = thread.CurrentThread(); System. out.println(T.GetName() +"Waiting to run Dosome method"); Thread.Sleep( +); System. out.println(T.GetName() +"Running Dosome method"); Thread.Sleep( +); System. out.println(T.GetName() +"Execution Dosome method complete"); }Catch(Exception e) {//Todo:handle exception}    }}

Operation Result:

Thread-1正在等待运行dosome方法Thread-1正在运行dosome方法Thread-1执行dosome方法完毕Thread-0正在等待运行dosome方法Thread-0正在运行dosome方法Thread-0执行dosome方法完毕
2.3 Mutex 2.3.1 Sync lock and mutual exclusion lock

Synchronous and mutex principles are the same, and there is a small difference in usage. When two threads call the same piece of code, and for two threads of the synchronization monitor, see the same code, that is the synchronous lock, but for a few pieces of code, with a synchronization monitor for access, a few pieces of code can not be executed concurrently, is the mutex

Package Com.javase.thread;/*** This code mainly demonstrates the use of mutexes* After using synchronized to decorate this code, as long as they synchronize the monitor object the same, then these pieces of code is mutually exclusive, multiple threads cannot execute the code at the same time *  * @authorGupan * */ Public classthreadsyncmatual {/*** thread T1 and T2 cannot invoke MethodA or MethodB methods at the same time to implement mutually exclusive relationships     *      * @param args     */     Public Static void Main(string[] args) {Boo Boo =New Boo(); Thread T1 =NewThread () { Public void Run() {Boo.MethodA();                }        }; Thread t2 =NewThread () { Public void Run() {Boo.MethodB();                }        }; T1.Start(); T2.Start(); }}classboo{ Public void MethodA(){Try{Thread T = thread.CurrentThread(); System. out.println(T.GetName() +"Executing a Method"); Thread.Sleep( +); System. out.println(T.GetName() +"Execute a method complete"); }Catch(Exception e) {//Todo:handle exceptionE.Printstacktrace(); }    } Public void MethodB(){Try{Thread T = thread.CurrentThread(); System. out.println(T.GetName() +"Executing the B method"); Thread.Sleep( +); System. out.println(T.GetName() +"Execute B method Complete"); }Catch(Exception e) {//Todo:handle exceptionE.Printstacktrace(); }    }}

JAVA04 thread synchronization Problem resolution--thread lock (synchronous lock, mutual exclusion lock)

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.