package com.bjsxt.demo0812Thread03;
/**
* @Auther: ldp
* @Date: 2019/8/12 20:35
* @Description:
*/
public class Test {
public static void main(String[] args) {
Runnable runnable = new TicketRunnable();
Thread thread1 = new Thread(runnable);
Thread thread2 = new Thread(runnable);
Thread thread3 = new Thread(runnable);
Thread thread4 = new Thread(runnable);
Thread thread5 = new Thread(runnable);
thread1.start();
thread2.start();
thread3.start();
thread4.start();
thread5.start();
}
}
`
在这里插入代码片
package com.bjsxt.demo0812Thread03;
/**
* @Auther: ldp
* @Date: 2019/8/12 20:31
* @Description:五个窗口同时售票,使用多线程完成
*/
public class TicketRunnable implements Runnable{
private int ticketNum = 100;
@Override
public void run() {
while (true){
if (ticketNum<=0){
break;
}
ticketOne();
}
}
//同步方法
private synchronized void ticketOne() {
try {
//改变线程
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (ticketNum<=0){
return;
}
System.out.println(Thread.currentThread().getName()+"窗口售票,余票为:"+ticketNum--);
}
}