Modify Exercise 1 to sell tickets. First, let it delay the network and solve the problem.
1) Synchronous Code Block
Class Ticket implements Runnable {private Integer num = 50; @ Overridepublic void run () {for (int I = 0; I <200; I ++) {sale ();}} private Object o = new Object (); // as the listening Object/*** ticket seller */public void sale () {synchronized (o) {if (num> 0) {try {Thread. sleep (1);} catch (InterruptedException e) {e. printStackTrace ();} System. out. println (Thread. currentThread (). getName () + "sold" + num -- + "tickets") ;}}} public class TicketDemo {public static void main (String [] args) {Runnable target = new Ticket (); new Thread (target, ""). start (); new Thread (target, "B "). start (); new Thread (target, "C "). start ();}}
2) Method 2: Synchronization Method
Class Ticket implements Runnable {private Integer num = 50; @ Overridepublic void run () {for (int I = 0; I <200; I ++) {sale ();}} /*** sell tickets */public synchronized void sale () {if (num> 0) {try {Thread. sleep (1);} catch (InterruptedException e) {e. printStackTrace ();} System. out. println (Thread. currentThread (). getName () + "sold" + num -- + "") ;}} public class TicketDemo {public static void main (String [] args) {Runnable target = new Ticket (); new Thread (target, ""). start (); new Thread (target, "B "). start (); new Thread (target, "C "). start ();}}
3) reentrant lock
Import java. util. concurrent. locks. reentrantLock; class Ticket implements Runnable {private Integer num = 50; private ReentrantLock lock = new ReentrantLock (); @ Overridepublic void run () {for (int I = 0; I <200; I ++) {sale () ;}/ *** sell tickets */public void sale () {lock. lock (); if (num> 0) {try {Thread. sleep (1); System. out. println (Thread. currentThread (). getName () + "sold" + num -- + "tickets");} catch (Exception e) {e. printStackTrace ();} finally {lock. unlock () ;}}} public class TicketDemo {public static void main (String [] args) {Runnable target = new Ticket (); new Thread (target, ""). start (); new Thread (target, "B "). start (); new Thread (target, "C "). start ();}}