代码如下:
public class Ticket1 implements Runnable {private int tickets = 100;@Overridepublic void run() {while (tickets > 0) {synchronized (Ticket.class) {if (tickets > 0) {tickets--;System.out.println(Thread.currentThread().getName() + "正在卖票,还剩下" + tickets + "张");}}try {// 休眠一秒,让执行的效果更明显Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}}}public static void main(String[] args) {Ticket1 ticket = new Ticket1();Thread t1 = new Thread(ticket, "窗口一:");Thread t2 = new Thread(ticket, "窗口二:");Thread t3 = new Thread(ticket, "窗口三:");t1.start();t2.start();t3.start();}
}