Synchronization control between multiple threads

Source: Internet
Author: User
Tags int size ticket


Problem:


Several threads running at the same time need to share one data and take into account each other's state and actions.


For example, when a thread operates on a shared data, it does not allow other threads to break it until the related operation is completed, otherwise it destroys the integrity of the data. That is, data shared by multiple threads allows only one thread to be in operation at the same time.


Implementation principle:


to ensure thread safety, use "lock flag";

when a thread A after a lock flag is obtained for an object, the thread B If you also want to get the lock flag for the object, you must wait for the thread A after the specified operation is completed and the lock flag is released, the lock flag for the object is obtained and the thread is executed B the operation in the.



Code implementation:


public class Producerandconsumer {/** * assumes that there are no tickets at the beginning of the ticket office, one thread is depositing the ticket, and the other thread is selling the ticket. * Create a new Ticket class object to have both the deposit ticket and the ticket thread access it. * Two threads share the same data object to implement operations on the same data */public static void Main (string[] args) {Tickets t=new tickets (10);//Create a new Ticket class object with the total number of votes as parameter new Pr Oducer (t). Start (); Create a ticket class object as a parameter and start new Consumer (T). Start ();//create a ticket thread with the same ticket class object and start the}}//ticket class Tickets{int number=0;//ticket int size ;//The total number of votes Boolean available=false; Indicates whether a ticket is currently available for sale public tickets (int size) {this.size=size;} constructor, incoming total votes parameter}//Save ticket thread class Producer extends Thread{tickets t=null;public Producer (Tickets t) {this.t=t;} Constructor: Take a ticket class as parameter @overridepublic void run () {while (t.number<t.size) {//Limit loop condition for the deposit sequence is less than the total number of votes synchronized (t) {// The lock flag of the Application object T System.out.println ("Producer puts ticket" + (++t.number)); t.available=true;//can buy tickets}//automatic release lock flag}}}//ticket Thread class Consumer extends Thread{tickets t=null;int i=0;public Consumer (Tickets t) {//constructor: Take a ticket class object as parameter this.t=t;} public void Run () {synchronized (t) {while (i<t.size) {//Loop condition is ticket number less than total if (t.available==true && i<= T.number) {//There is a ticket available for sale and less than the current ticket number system.Out.println ("Consumer buys ticket" + (++i));} if (i==t.number) {//Pawn ticket is sold to the current serial number, it is not available for sale T.available=false;}}}}


There is only one lock flag for an object, so the mutex effect of different threads can be realized by contention on an object lock flag. When a thread obtains a lock flag, other threads that need to change the flag are only waiting.


Alternatively, you can add this keyword to the method:


Ticket method public synchronized void sell () {if (!available) {///If no ticket is saved, the ticket thread waits for try{wait ();} catch (Exception e) {}system.out.println ("Consumer buys ticket" + (number)), available=false;notify ();//Ticketing wake-up ticket thread start deposit if (number==size) {number=size+1;//After the last ticket has been sold, set an end flag}//number>size indicates the end of the ticket}}







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

Synchronization control between multiple threads

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.