Thread basics Article 2: synchronization between multiple threads and Article 2 Multithreading

Source: Internet
Author: User

Thread basics Article 2: synchronization between multiple threads and Article 2 Multithreading

Preface; Hello everyone, this time we will learn the synchronization operations between threads:

1. If we want to use multiple threads to operate the same object or data, we must first know why we need to use synchronization?

 

Java allows multi-thread concurrency control when multiple threadsAt the same timeOperationShared Resource Variables(For example, adding, deleting, modifying, and querying the same data) will lead to inaccurate data and mutualConflict, So joinSynchronization lockTo avoid being called by other threads before the thread completes the operation, so as to ensureUniquenessAndAccuracy.

 

From this, we can get the concept of synchronization:

 

The so-called synchronization means that when a function call is sent, the call will not be returned until the result is obtained, and other threads cannot call this method. According to this definition, most functions are called synchronously (such as sin and isdigit ). But in general, when we talk about synchronization and Asynchronization, we are referring to the tasks that require the collaboration of other components or a certain amount of time. For example, the Window API function SendMessage. This function sends a message to a window. This function does not return a message before the recipient finishes processing the message. After the other party completes processing, the function returns the LRESULT value returned by the message processing function to the caller.

 

In multi-thread programming, some sensitive data cannot be accessed by multiple threads at the same time.Synchronous accessTechnology to ensure that data is available at most at any timeOne thread accessTo guaranteeData Integrity.

 

2. How to Use synchronization?

 

After a simple search on the Internet, I found that there are 5-7 synchronous methods. In fact, the principle in synchronization is not changed, so today we will simply look at one:

 

1. UseSynchronizedKeyword modifier and code block

 

Thread security: synchronized

 

(1)Method locking

Public synchronized void (){

// The shared object can be accessed in this method.

}

 

(2)Code block locking

Public void B (){

Synchronized (shared object ){

I ++;

}

}

Note: synchronization is a highly open operation, so you should minimize the amount of synchronization content. Generally, there is no need to synchronize the entire method. Use the synchronized code block to synchronize key code.

   

3. As mentioned above, we will go on to the ticket sales system in the previous article to add multiple windows to sell tickets, that is, to add multiple threads to demonstrate thread synchronization:

 

(1) Demonstration Background: Suppose we have a ticketing system with a total of 50 tickets. There is only one window. Now, due to the recent popularity of business, the waiting time of customers is long, so now we need to add three windows, so writing to the code is to add three threads (a window represents a thread for ticket sales, and there are four threads in total)

 

(2) the classes and methods of the Code are the same as those of the previous article. In the test phase, three threads are added. The Code is as follows:

 

     1) Implement the Runnable interface to sell tickets 

/*** @ Window in the functon Ticketing System * @ author (Nickname: Sink top) * @ time 2017.12.1 */package TicketShop; // This class shows the thread public class SaleTicketsbyRannable implements Runnable {// public Tickets tic class for obtaining Tickets; // public SaleTicketsbyRannable (Tickets tic) with Parameters) {super (); this. tic = tic;} // implement the run method in the Runnable interface, and rewrite @ Override public void run () {// while to determine if the number of votes is zero to stop selling while (tic. getCount ()> = 0) {sale () ;}// method of ticket selling (Note: sy here The nchronized keyword plays this key role, because it can complete thread synchronization. It can be said that it is a major contributor, haha) public synchronized void sale () {// get the name of the current thread, intuitively shows which Thread is String threadname = Thread. currentThread (). getName (); // determines if (tic. getCount ()> 0) {// print the number of tickets sold in the output: System. out. println (threadname + ":" + tic. getCount () + "tickets sold! "); // The total number of tickets to be sold is reduced by 1 tic. setCount (tic. getCount ()-1); try {// The Thread is sleeping for 0.2 seconds, but it is convenient to see the demo effect Thread. currentThread (). sleep (200);} catch (InterruptedException e) {e. printStackTrace () ;}} else {// when the number of votes is 0, the output "the ticket is sold empty" // because while is still in the loop, you need to subtract one, otherwise, there will be an infinite endless loop tic. setCount (tic. getCount ()-1); System. out. println (threadname + "ticket sold empty! ") ;}}// Set and get methods of the ticket class public Tickets getTic () {return tic;} public void setTic (Tickets tic) {this. tic = tic ;}}

 

 

    

      2) ticket categories

 

/*** @ Total number of votes in the functon Ticketing System * @ author (Nickname: Sink top) * @ time 2017.12.1 */package TicketShop; // This class is the ticket to be sold, all the Tickets to be sold should be taken from here public class Tickets {// because it is a demo, there are not so many attribute values in the Ticket class // The total number of Tickets private int count; // construct public Tickets (int count) {super (); this. count = count ;}// public Tickets () {super () ;}// set and get Methods public int getCount () {return count ;} public void setCount (int count) {this. count = count ;}}

     

     3) demonstrate the test class of the ticket selling result in four windows (Note: This is different from the previous one and is also the most important part)

 

/*** @ Functon ticketing system demonstration (using the method to implement the Rannble Interface) * @ author (Nickname: Sink top) * @ time 2017.12.1 */package TicketShop; public class TestSale {public static void main (String [] args) {// The object class of a new ticket, and give it 50 Tickets tic = new Tickets (50 ); // create SaleTicketsbyRannable str = new SaleTicketsbyRannable (tic); // Therefore, the object does not inherit the Thread class, so it cannot be called directly. // a new Thread is required. Now four new threads are required, because there are four windows, Thread st1 = new Thread (str, "Window 1"); // after each new Thread, add a name, to distinguish the four windows Thread st2 = new Thread (str, "window 2"); Thread st3 = new Thread (str, "window 3"); Thread st4 = new Thread (str, "Window 4"); // execute st1.start (); st2.start (); st3.start (); st4.start ();}}

 

  

    4) demonstration effect (because there is too much data, it will be omitted in the middle)

 

 

Window 1: 50th tickets sold!
Window 4: 49th tickets sold!
Window 4: 48th tickets sold!
Window 3: 47th tickets sold!

...
...

Window 4: 11th tickets sold! Window 1: 10th tickets sold! Window 4: 9th tickets sold! Window 4: 8th tickets sold! Window 3: 7th tickets sold! Window 3: 6th tickets sold! Window 2: 5th tickets sold! Window 3: 4th tickets sold! Window 3: 3rd tickets sold! Window 3: 2nd tickets sold! Window 4: 1st tickets sold! The ticket for Window 4 is sold out! The ticket for window 1 is sold out! The ticket for window 3 is sold out! Window 2 ticket sold empty!

 

In the demo, you can see that the four ticket sales windows sell the same ticket at the same time, and the ticket sales will not appear in the other windows after the sale, however, in the internal mechanism, the execution is performed one by one, and there is no sequence in the execution. That is to say, the thread obtains the resource first and the thread executes the task first. After the ticket is sold out, if you access the window again, the message "tickets sold out" is displayed! This is the synchronization between threads!

Well, this is the thread synchronization in this article. It's time to talk to everyone about sayGoodbay. Here, I wish you all the more and more on the road to learning Java!

(After this article is completed, it indicates that you have taken the second step of the thread. What are the number of steps you have asked me? Honestly, I can't see my head, haha, every piece of knowledge is profound and profound. It is true that the more you learn, the better !)

(I will tell you quietly. The third article is to implement communication between threads. If you are interested, let's take a look !)

 

Related Article

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.