用多线程的同步来实现多窗口卖票功能

package gxx22;
public class SellTicketDemo {
public static void main(String[] args) {
// 创建资源对象
SellTicket st1 = new SellTicket();
// 创建3个线程对象
Thread t1 = new Thread(st1, "窗口1");
Thread t2 = new Thread(st1, "窗口2");
Thread t3 = new Thread(st1, "窗口3");
// 启动线程
t1.start();
t2.start();
t3.start();
}
}


class SellTicket implements java.lang.Runnable {
// 定义100张票
private int tickets = 100;
// 创建锁对象
private Object obj = new Object();
        //重写run()
public void run() {
while (true) {
synchronized (obj) {
if (tickets > 0) {
System.out.println(Thread.currentThread().getName() + "正在出售第" + (tickets--) + "张票");
}
}
}
}

}运行结果:

用多线程的同步来实现多窗口卖票功能_第1张图片

你可能感兴趣的:(技术入门)