/**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