/** * 需求:铁路售票,一共100张,通过四个窗口卖完. */ public static void main(String[] args) { new Ticket().start(); new Ticket().start(); new Ticket().start(); new Ticket().start(); }}class Ticket extends Thread { private static int ticket = 100; //private static Object obj = new Object(); //如果用引用数据类型成员变量当作锁对象,必须是静态的 public void run() { while(true) { synchronized(Ticket.class) { if(ticket <= 0) { break; } try { Thread.sleep(10); //线程1睡,线程2睡,线程3睡,线程4睡 } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(getName() + "...这是第" + ticket-- + "号票"); } } }
/** * @param the args * railway station example of selling tickets with the implementation of the Runnable interface */public static void main (string[] args) {MyT Icket MT = new Myticket (); New Thread (MT). Start (); New Thread (MT). Start (); New Thread (MT). Start (); New Thread (MT). Start (); /*thread T1 = new Thread (MT); Starting a thread multiple times is illegal t1.start (); T1.start (); T1.start (); T1.start (); */}}class Myticket implements Runnable {private int tickets = 100; @Override public void Run () {while (true) {synchronized (this) {if (tickets <= 0) { Break } try {Thread.Sleep (10); Thread 1 sleeps, thread 2 sleeps, thread 3 sleeps, thread 4 sleeps} catch (Interruptedexception e) {e.printstacktrace (); } System.out.println (Thread.CurrentThread (). GetName () + "... This is the first "+ tickets--+" ticket "); } } }
Multithreading-Railway ticketing learning