版权声明:本博客为记录本人学习过程而开,内容大多从网上学习与整理所得,若侵权请告知! https://blog.csdn.net/Fly_as_tadpole/article/details/84064058
假设车库有3个车位(可以通过boolean[]数组来表示车库)可以停车,写一个程序模拟多个用户开车离开,停车入库的效果。注意:车位有车时不能停车。
1)使用阻塞队列来实现(BlockingQueue<T>)
Producer类
package com.多线程停车问题;
import java.util.concurrent.BlockingQueue;
public class Producer extends Thread{
private BlockingQueue<Boolean>bq;
private String name;
public Producer(BlockingQueue<Boolean> bq, String name) {
super();
this.bq = bq;
this.name = name;
}
public void run(){
try{
bq.put(true);
System.out.println(this.name+"停入");
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
Consumer类
package com.多线程停车问题;
import java.util.concurrent.BlockingQueue;
public class Consumer extends Thread{
private BlockingQueue<Boolean> bq;
public Consumer(BlockingQueue<Boolean> bq) {
super();
this.bq = bq;
}
public void run(){
try{
bq.take();
System.out.println("驶出");
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
测试类:只有当有车子驶出,也就是有空余的停车位的时候,才能够停车。只有有车子的时候才能驶出。
package com.多线程停车问题;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class Test {
public static void main(String[]args){
BlockingQueue<Boolean>bq = new ArrayBlockingQueue<>(3);
new Producer(bq,"摩托车").start();
new Producer(bq,"保时捷").start();
new Producer(bq,"宝马").start();
new Producer(bq,"奥迪").start();
new Consumer(bq).start();
}
}
2)使用synchronized同步实现
/*
* 定义一个停车场类,两个线程共享停车场,利用同步停车场对象实现停车和出库操作
* 当停车场满时,wait(),等待取车操作
* 当停车场为空时,wait(),等待有车停入
*/
//停车场类
class Park{
boolean[] park = new boolean[3];
//state变量定义停车场的剩余车辆
private int state =3;
public synchronized void CarIn(int i) {
try {
while(state==0) {
System.out.println("目前空余车位为:"+state+"请等待");
wait();
}
System.out.println(i+"车位停车成功");
state=state-1;
System.out.println("目前剩余车位为:"+state);
notify();
}
catch(InterruptedException e){
e.printStackTrace();
}
}
public synchronized void CarOut(int i) {
try {
while(state==3) {
//System.out.println("目前空余车位为:"+state+"请等待");
wait();
}
System.out.println(i+"车驶出");
state=state+1;
System.out.println("目前剩余车位为:"+state);
notify();
}
catch(InterruptedException e){
e.printStackTrace();
}
}
}
class CarInThread extends Thread{
Park park=new Park();
public CarInThread(Park park) {
this.park=park;
}
public void run() {
super.run();
for(int i=1;i<5;i++){
park.CarIn(i);
}
}
}
class CarOutThread extends Thread{
Park park=new Park();
public CarOutThread(Park park) {
this.park=park;
}
public void run() {
super.run();
for(int i=1;i<5;i++){
park.CarOut(i);
}
}
}
public class SynchronizedTest {
public static void main(String[] args) {
Park park = new Park();
new CarInThread( park).start();
new CarOutThread(park).start();
}
}