- <div class="blockcode"><blockquote><div class="blockcode"><blockquote>package cn.itheima.demo;
- /**
- * 这是售票窗口
- *
- * @author pinger
- *
- */
- public class SealWindow {
- public static void main(String[] args) {
- // 创建共享资源
- Ticket t = new Ticket();
- TicketSealCenter gt = new TicketSealCenter(t);
- // 设置线程
- Thread t1 = new Thread(gt, "窗口一");
- Thread t2 = new Thread(gt, "窗口二");
- Thread t3 = new Thread(gt, "窗口三");
- // 线程启动
- t1.start();
- t2.start();
- t3.start();
- }
- }
复制代码
package cn.itheima.demo;
/**
* 这是售票中心
*
* @author pinger
*
*/
public class TicketSealCenter implements Runnable {
// 设置构造,共享资源对象
private Ticket t;
public TicketSealCenter(Ticket t) {
this.t = t;
}
@Override
public void run() {
while (true) {
synchronized (t) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 消费资源
Ticket.sellTicket();
}
}
}
}
package cn.itheima.demo;
/**
* 这是一个票的基本信息的类
*
* @author pinger
*
*/
public class Ticket {
// 票信息
private static int tickets = 100;
// 售票的方式
public static void sellTicket() {
if (tickets > 0) {
// 进行消费
System.out.println(Thread.currentThread().getName() + "正在售"
+ Ticket.tickets-- + "张票");
}
}
}
|