package test; /** * author:songyan * date: 2019/11/10 **/ public class demo1 { public static void main(String[] args) { Tickert t = new Tickert(); Thread t1 = new Thread(t); Thread t2 = new Thread(t); Thread t3 = new Thread(t); Thread t4 = new Thread(t); t1.start(); t2.start(); t3.start(); t4.start(); } } class Tickert implements Runnable { private int number = 100;//一共一百张票 Object obj = new Object(); @Override public void run() { while (true) { synchronized (obj) { if (number > 0) { System.out.println("ticket " + number--); } } } } }
通过加锁防止出现错票