实现开启三个线程卖票
public class Ticket implements Runnable {
int ticket = 100;
//加入锁对象
Object lock = new Object();
@Override
public void run() {
while (true) {
synchronized (lock) {
if (ticket > 0) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
String name = Thread.currentThread().getName();
System.out.println(name + ": 正在买票" + ticket--);
}
}
}
}
public static void main(String[] args) {
Ticket ticket = new Ticket();
Thread t1 = new Thread(ticket, "窗口一");
Thread t3 = new Thread(ticket, "窗口三");
Thread t2 = new Thread(ticket, "窗口二");
t1.start();
t2.start();
t3.start();
}