zoukankan      html  css  js  c++  java
  • java多线程模拟停车位问题

    /**
     * 
     */
    package Synchronized;
    
    /**
     * @author libin
     *
     */
    public class CarTest {
    	public static void main(String[] args) {
    		CarSet car1 = new CarSet();
    		Thread t1 = new InThread("1",car1);
    		Thread t2 = new InThread("2",car1);
    		Thread t3 = new InThread("3",car1);
    		Thread t4 = new OutThread("4",car1);
    		Thread t5 = new OutThread("5",car1);
    		t1.start();
    		t2.start();
    		t3.start();
    		t4.start();
    		t5.start();
    	}
    
    }
    class InThread extends Thread  //入库线程
    {
    	String name;
    	CarSet car;
    	public InThread(){}
    	public InThread(String name,CarSet car)
    	{
    		super(name);
    		this.car = car;
    	}
    	public void run()
    	{
    		car.CarIn();
    	}
    }
    class OutThread extends Thread
    {
    	String name;
    	CarSet carSet;
    	public OutThread(){}
    	public OutThread(String name,CarSet carSet)
    	{
    		super(name);
    		this.carSet = carSet;
    	}
    	public void run()
    	{
    		carSet.CarOut();
    	}
    }
    
    class CarSet
    {
    	//String carName;
    	private boolean[] place = new boolean[3];
    	public CarSet(){}
    //	public CarSet(String carSetName)
    //	{
    //		this.carName = carSetName;
    //	}
    	public synchronized void CarIn()
    	{
    		try
    		{
    			if(place[0]&&place[1]&&place[2])
    			{
    				System.out.println("车位已满,请等待。");
    				wait();
    			}
    			for(int i = 0; i < 3; i++)
    			{
    				if(place[i] == false)//车位空,可以入库
    				{
    					System.out.println(Thread.currentThread().getName()+"可以入"+i+"号库");
    					place[i] = true;
    					notifyAll();
    					break;
    				}
    				
    			}
    		}
    		catch(InterruptedException e)
    		{
    			e.printStackTrace();
    		}
    		
    	}
    	public synchronized void CarOut()
    	{
    		try
    		{
    			if(!(place[0]||place[1]||place[2]))
    			{
    				wait();
    			}
    			for(int i = 0; i < 3; i++)
    			{
    				if(place[i] == true)//车在库内,可以出库
    				{
    					System.out.println(Thread.currentThread().getName()+"可以从"+i+"号库出库");
    					place[i] = false;
    					notifyAll();
    					break;
    				}
    			}
    		}
    		catch(InterruptedException e)
    		{
    			e.printStackTrace();
    		}
    		
    	}
    }
    
  • 相关阅读:
    springMVC的@RequestMapping的参数和用法
    springMVC的helloword
    eclipse 导入MyEclipse创建的web项目该如何启动?
    解决mysql中文乱码
    java核心技术 卷1 基础知识—对象与继承
    Java核心技术 卷1 基础知识—概述、环境
    python爬虫框架之scrapy的快速上手
    如何评测软件工程知识技能水平
    金融文本挖掘的业务领域建模
    金融文本挖掘中的针对业务的用例建模
  • 原文地址:https://www.cnblogs.com/masterlibin/p/4800692.html
Copyright © 2011-2022 走看看