Java Synchronization code block

Source: Internet
Author: User
Tags ticket

/**ABC Three ticket sales window for 50 tickets. Requirements: can be sold at the same time, and cannot sell overlapping, and can not exceed 50 synchronous code block synchronized (object) {     synchronous code block;} objects are like locks, A thread holding a lock can execute a thread that does not hold a lock in the synchronization, even if it obtains the CPU's executor. Synchronization Prerequisites: 1. Multithreaded code blocks need to be synchronized, that is, the code in run needs to be synchronized. Synchronizing shared data 2. You must use the same lock for multiple threads before you need synchronization benefits: Improve multithreading security problems: Multiple threads need to determine the lock, more consumption of resources */class tickt implements runnable  //extends Thread{{    private int tickt=10000;     object obj = new object ();         public  void run () {                         while (True) {              synchronized (obj) {                     if (tickt>0) {                              //try{thread.sleep (100);} catch (interruptedexception e) {}                     system.out.println (Thread.CurrentThread (). GetName () + "conductor sells:" +  tickt-- + "Ticket");                  }                            }      }                 }     }class saletickt{    public static void main (String[]args) {        tickt a = new tickt ();          thread t1 = new thread (a);         Thread t2 = new thread (a);         thread t3  = new thread (a);         thread t4 = new  thread (a);         t1.start ();         t2.start ();         t3.start ();         t4.start ();     }}


Java Synchronization code block

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.