Java multithreaded Walkthrough (iii)------thread synchronization

Source: Internet
Author: User

Java Multithreading (a) Introduction to------concept: http://www.cnblogs.com/ysocean/p/6882988.html

Java multithreaded Walkthrough (ii)------How to create processes and threads: http://www.cnblogs.com/ysocean/p/6883491.html

After describing how to create a process and a thread, let's look at an example:

  Using multi-threaded simulation 3 windows sell tickets

The first method: Inherit the Thread class

 Creating a window class Ticketsell

Package Com.ys.thread;public class Ticketsell extends thread{//defines a total of 50 tickets, notice that the declaration is static, indicating that several Windows share private static int num = 5 0;//calls the parent class constructor method, naming the thread public Ticketsell (string string) {super (string);}  @Overridepublic void Run () {///The ticket is sold for 50 times (int i = 0; i <; i + +) {if (num > 0) {try {sleep (10);//analog sell ticket takes a certain amount of time} catch (Interruptedexception e) {//Because the run () method of the parent class does not throw any exception, according to the principle of inheritance, the subclass throws an exception that cannot be greater than the parent class, so we cannot throw an exception here E.printstacktrace ();} System.out.println (This.currentthread (). GetName () + "sell one ticket, remaining" + (--num) + "Zhang");}}}

To create the main thread test:

Package Com.ys.thread;public class Testticket {public static void main (string[] args) {//Create 3 windows Ticketsell t1 = new Ticke Tsell ("a Window"); Ticketsell t2 = new Ticketsell ("b window"); Ticketsell t3 = new Ticketsell ("c window");//start 3 windows to buy tickets T1.start (); T2.start (); T3.start ();}}

Result: Here we omit some, according to the computer configuration, the result will randomly appear different

b window sell a ticket, the remaining 48 a window sell a ticket, the remaining 47 c window sell a ticket, the remaining 49 c window sell a ticket, the remaining 46 b window sell a ticket, the remaining 44 a window sell a ticket, the remaining 45 a window sell a ticket, the remaining 43 Zhang ... c window to sell a ticket, the remaining 5 a window sells a ticket, the remaining 4 b window sells a ticket, the remaining 3 a window sells a ticket, the remaining 2 Windows c window sells a ticket, the remaining 3 b window sells a ticket, the remaining 1 Windows C window sells a ticket, the remaining 0 a window sells a ticket, the remaining-1 sheets

  

Second approach: Implement the Runnable interface

Creating a window class Ticketsellrunnable

Package Com.ys.thread;public class Ticketsellrunnable implements runnable{//defines a total of 50 tickets, the inheritance mechanism to open threads, resources are shared, so do not add staticprivate int num = 50, @Overridepublic void Run () {///votes are sold out for (int i = 0; i <; i + +) {if (num > 0) {try {//modulo) The time required to sell a ticket thread.sleep (10);} catch (Interruptedexception e) {e.printstacktrace ();} System.out.println (Thread.CurrentThread (). GetName () + "sell one ticket, remaining" + (--num) + "Zhang");}}}

To create the main thread test:

Package Com.ys.thread;public class Ticketsellrunnabletest {public static void main (string[] args) {ticketsellrunnable T = New Ticketsellrunnable (); thread T1 = new Thread (t, "a Window"); Thread t2 = new Thread (t, "b window"); thread t3 = new Thread (t, "c window"); T1.start (); T2.start (); T3.start ();}}

The result: We also omit some of the middle results for the sake of space.

b window sell a ticket, the remaining 49 c window to sell a ticket, the remaining 48 a window sell a ticket, the remaining 49 b window sell a ticket, the remaining 47 a window sell a ticket, the remaining 45 Zhang ... A window sells a ticket, the remaining 4 c window sells a ticket, the remaining 5 a window sells a ticket, the remaining 3 b window sells a ticket, the remaining 2 Windows c window sells a ticket, the remaining 1 b window sells a ticket, the remaining 0 a window sells a ticket, the remaining-2 c window sells a ticket, the remaining 1 sheets

  

Results analysis: There is a negative number of votes in the case, which in real life certainly does not exist, then why does this happen?

  

Solution Analysis: We cannot allow more than two threads to enter the IF (num>0) code block at the same time, otherwise the above error will occur. There are three ways to solve this problem:

1. Using synchronous code blocks

2. Using the synchronization method

3. Using lock mechanism

①, using synchronous code blocks

Syntax: synchronized (Sync Lock) {    //code for synchronous operation          } synchronization Lock: In order to ensure that each thread performs atomic operations properly, the Java thread introduces a synchronization mechanism; a synchronous lock is also called a synchronous listener, a synchronous listener, a mutex , any object that the Java program uses can be used as a synchronous listener, but generally we take the common resource of concurrent access as the synchronous Listener Note: The synchronization lock must be guaranteed to be deterministic, not relative to the thread is the object of change; At any time, a maximum of one thread is allowed to get a sync lock. Who gets the lock who gets into the code block while the other threads can only wait outside

Instance:

public void Run () {///votes divided 50 times after sold for (int i = 0; i <; i + +) {//Here we use the current object's bytecode object as the synchronization lock synchronized (This.getclass ()) {if (n Um > 0) {try {//simulate the time required to sell a ticket thread.sleep;} catch (Interruptedexception e) {e.printstacktrace ()} System.out.println (Thread.CurrentThread (). GetName () + "sell one ticket, remaining" + (--num) + "Zhang");}}}

  

2. Using the synchronization method

Syntax: Use synchronized keyword modification method

@Overridepublic void Run () {///The ticket is sold for 50 times (int i = 0; i <; i + +) {sell ();}} Private synchronized void Sell () {if (num > 0) {try {//simulate the time required to sell a ticket thread.sleep;} catch (Interruptedexception e) { E.printstacktrace ();} System.out.println (Thread.CurrentThread (). GetName () + "sell one ticket, remaining" + (--num) + "Zhang");}}

  Note: You cannot modify the run () method directly with synchronized, because if you do this, it will always be the first thread to enter it, and the thread will finish all operations, that is, all the tickets are sold out.

3. Using lock mechanism

  

public interface Lock

Main methods:

Common Implementation classes:

public class Reentrantlockextends objectimplements Lock, Serializable
A reentrant mutex lock has the same basic behavior and semantics as an implicit monitoring lock using the Synchronized method and the statement access, but with extended functionality.

Example:

Package Com.ys.thread;import Java.util.concurrent.locks.lock;import Java.util.concurrent.locks.ReentrantLock; public class Ticketsellrunnable implements runnable{//defines a total of 50 tickets, the inheritance mechanism to open the thread, the resource is shared, so do not add staticprivate int num = 50;//Create a Lock Object Lock L = new Reentrantlock (), @Overridepublic Void Run () {//votes divided 50 times sold for (int i = 0; i <; i + +) {//Get lock L.lock (); try {if (num > 0) {//Thread.Sleep time required to simulate selling one ticket (10); System.out.println (Thread.CurrentThread (). GetName () + "sell one ticket, remaining" + (--num) + "Zhang");}} catch (Exception e) {e.printstacktrace ();} finally{//release lock L.unlock ();}}} private void Sell () {}}

  

  

Java multithreaded Walkthrough (iii)------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.