//用两个线程模拟存票、售票过程,直到售完为止 存票->售票->存票->售票->存票...
//wait() vs sleep():wait放弃CPU资源同时让出控制权(释放已有对象的互斥锁),sleep还是占有
public class App11_8 {
public static void main(String[] args) {
Tickets t = new Tickets(10); // 新建一个票类对象t,总票数作为参数
new Producer(t).start(); // 以票类对象t为参数创建存票线程 对象 ,并启动
new Consumer(t).start(); // 以同一票类对象t为参数创建售票线程 对象,并启动
}
}
class Tickets // 票类
{
protected int size; // 总票数
int number = 0; // 票号
boolean available = false; // 当前有票可售
public Tickets(int size) // 构造方法
{
this.size = size;
}
public synchronized void put() // 同步方法,存票
{
if (available) // 有票可售,则存票进程等待
{
try {
wait();
} catch (Exception e) {
}
}
System.out.println("存入第【" + (++number) + "】号票");
available = true;
notify(); // 存票后唤醒售票进程开始售票
}
public synchronized void sell() // 同步方法,售票
{
if (!available) // !!! !available 如果没票,则售票进程等待
{
try {
wait();
} catch (Exception e) {
}
}
System.out.println("售出第【" + number + "】号票");
available = false;
notify(); // 唤醒存票进程
if (number == size)
number = size + 1;
}
}
class Producer extends Thread // 存票线程类
{
Tickets t = null;
public Producer(Tickets t) // 构造方法,使两线程共享票类对象,所以只有一个对象t
{
this.t = t;
}
public void run() {
while (t.number < t.size)
t.put();
}
}
class Consumer extends Thread // 售票线程类
{
Tickets t = null;
public Consumer(Tickets t) {
this.t = t;
}
public void run() {
while (t.number <= t.size)
t.sell();
}
}
App11_08_用两个线程模拟存票、售票过程
最新推荐文章于 2023-04-07 21:07:16 发布