用JAVA语言实现司机与售票员pv操作
时间: 2023-09-14 09:11:24 浏览: 52
假设司机和售票员是两个线程,可以使用Java中的synchronized关键字实现pv操作。
具体实现如下:
1. 创建一个共享变量count,代表可用的座位数。
```
private int count = 10;
```
2. 在售票员线程中,使用synchronized关键字锁住count变量,当count为0时,售票员线程进入等待状态(wait),直到司机线程释放锁并通知售票员线程(notify)。
```
public synchronized void p() {
while (count == 0) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
count--;
System.out.println("售票成功,当前可用座位数:" + count);
notify();
}
```
3. 在司机线程中,使用synchronized关键字锁住count变量,当count为10时,司机线程进入等待状态(wait),直到售票员线程释放锁并通知司机线程(notify)。
```
public synchronized void v() {
while (count == 10) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
count++;
System.out.println("司机上车,当前可用座位数:" + count);
notify();
}
```
4. 在主函数中创建司机和售票员线程,分别执行p()和v()方法,模拟售票过程。
```
public static void main(String[] args) {
Driver driver = new Driver();
TicketSeller seller = new TicketSeller(driver);
new Thread(seller).start();
new Thread(driver).start();
}
```
完整代码如下:
```
public class Driver implements Runnable {
private int count = 10;
public synchronized void v() {
while (count == 10) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
count++;
System.out.println("司机上车,当前可用座位数:" + count);
notify();
}
@Override
public void run() {
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
v();
}
}
}
public class TicketSeller implements Runnable {
private Driver driver;
public TicketSeller(Driver driver) {
this.driver = driver;
}
public synchronized void p() {
while (driver.count == 0) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
driver.count--;
System.out.println("售票成功,当前可用座位数:" + driver.count);
notify();
}
@Override
public void run() {
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
p();
}
}
}
public class Main {
public static void main(String[] args) {
Driver driver = new Driver();
TicketSeller seller = new TicketSeller(driver);
new Thread(seller).start();
new Thread(driver).start();
}
}
```