多线程卖票代码
package com.loaderman.syn; public class Demo_Ticket { /** * 需求:铁路售票,一共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-- + "号票"); } } } }
package com.loaderman.syn; public class Demo_Ticket { /** * @param args * 火车站卖票的例子用实现Runnable接口 */ public static void main(String[] args) { MyTicket mt = new MyTicket(); new Thread(mt).start(); new Thread(mt).start(); new Thread(mt).start(); new Thread(mt).start(); /*Thread t1 = new Thread(mt); //多次启动一个线程是非法的 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); //线程1睡,线程2睡,线程3睡,线程4睡 } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "...这是第" + tickets-- + "号票"); } } } }
最后,关注【码上加油站】微信公众号后,有疑惑有问题想加油的小伙伴可以码上加入社群,让我们一起码上加油吧!!!