1. The realization of the ticket purchase case
Note: 100 tickets are sold at multiple windows at the same time, and the ticket sales will stop when they are sold out.
Ideas:
public class MyRunnable implements Runnable{
private int ticket = 100;
@Override
public void run() {
while (ticket >= 0) {
if(ticket == 0){
break;
}else {
ticket--;
System.out.println(Thread.currentThread().getName() + "卖了一张票,还剩" + ticket + "张");
}
}
}
}
public class Demo {
public static void main(String[] args) {
MyRunnable mr1 = new MyRunnable();
Thread t1 = new Thread(mr1);
Thread t2 = new Thread(mr1);
Thread t3 = new Thread(mr1);
t1.setName("#窗口一#");
t2.setName("##窗口二##");
t3.setName("###窗口三###");
t1.start();
t2.start();
t3.start();
}
}