package day;public class Mytd implements Runnable { //通过实现Runnable接口来实现多线程 private int ticketcount = 100; Object ob = new Object(); //加锁 private int m = 100; public Mytd(int t) { //有参构造方法 this.ticketcount = t; this.m = t; } public Mytd() { //无参构造方法 } public void sellticket() { //卖票方法 synchronized (ob) { //同步线程锁 if (ticketcount > 0) { ticketcount--; int num = this.m - ticketcount; System.out.println(Thread.currentThread().getName() + "卖出第" + num + "张票,还剩" + ticketcount + "张票"); } else { System.out.println("票已经卖完"); return; } } } @Override public void run() { while (ticketcount > 0) { sellticket(); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } }}
package day;public class Work { public static void main(String[] args) { Mytd run = new Mytd(100); Thread th1 = new Thread(run,"东风路售票点"); //开启五个线程 Thread th2 = new Thread(run,"吉祥路售票点"); Thread th3 = new Thread(run,"从动路售票点"); Thread th4 = new Thread(run,"文明路售票点"); Thread th5 = new Thread(run,"好听路售票点"); th1.start(); th2.start(); th3.start(); th4.start(); th5.start(); }}