生产者消费者代码--线程同步总结

 

1.线程/进程的概念

2.创建和启动线程的方式

3常用方法:

    sleep()

    jion()

    yield()

    wait()

    notify()

    notifyAll()

4.synchronized

 

 

 

 

/**
 * 生产者消费者(以生产汽车 ,销售汽车为例)
 * 
 * @author Solarisy
 * 
 */
public class TestProducerConsumer {

	public static void main(String[] args) {
		WareHouse wh = new WareHouse();
		Producer per = new Producer(wh);
		Consumer cer = new Consumer(wh);

		new Thread(per).start();
		new Thread(cer).start();
	}

}

/**
 * 汽车
 * 
 * @author Solarisy
 * 
 */
class Car {
	/* 汽车编号 */
	private int id;

	Car(int id) {
		this.id = id;
	}

	public String toString() {
		return "" + id;
	}
}

/**
 * 大商店
 * 
 * @author Administrator
 * 
 */
class WareHouse {
	/* 存放汽车的车库 */
	Car[] carport = new Car[6];
	/* 车位号 */
	int index;

	/**
	 * 生产一辆汽车,将汽车停入车位 
	 * 同步方法
	 * 
	 * @param car
	 */
	public synchronized void in(Car car) throws Exception {
		while (index == 6) {
			System.out.println("车位满了,生产等待中......");
			this.wait();
		}

		carport[index] = car;
		System.out.println("The car was produce that id is :" + car
				+ " 放入车位 = " + index);
		this.notify();
		index++;
	}

	/**
	 * 销售一辆汽车,将汽车开车车位 
	 * 同步方法
	 * 
	 */
	public synchronized Car out() throws Exception {
		while (index <= 0) {
			System.out.println("车库空了。‘有钱竟然买不到汽车,我回家等着......’");
			this.wait();
		}
		index--;
		System.out.println( carport[index] + "号汽车被顾客买走了...");
		this.notify();
		return carport[index];
	}
}

/**
 * 生产者
 * 
 * @author Solarisy
 * 
 */
class Producer implements Runnable {
	WareHouse wh;

	Producer(WareHouse wh) {
		this.wh = wh;
	}

	/* 生产汽车 */
	public void produce() throws Exception {
		for (int i = 0; i < 20; i++) {
			Car car = new Car(i);
			wh.in(car);
		}
	}

	public void run() {
		try {
			produce();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

/**
 * 消费者
 * 
 * @author Solarisy
 * 
 */
class Consumer implements Runnable {
	WareHouse wh;

	Consumer(WareHouse wh) {
		this.wh = wh;
	}

	/* 买车 */
	public void buy() throws Exception {
		for (int i = 0; i < 20; i++) {
			wh.out();
		}
	}

	public void run() {
		try {
			buy();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值