java

来源:互联网 发布:网络交易平台怎么做 编辑:程序博客网 时间:2024/04/30 02:25
package dayl018.homework.Fruit;/** * * Description: 一个生产者类,一个消费者类
* Copyright (c) , 2016, kliine
* This program is protected by copyright laws.
* Program Name:Test1.java
* Date: 2016年1月25日 下午10:03:29 * * @author 颜克林 * @version : 1.0 */public class Test3 {private Fruit fruit;// 生产者父亲class Father implements Runnable {private int cnt = 0;@Overridepublic void run() {while (true) {synchronized ("") {while (fruit != null) {try {"".wait();} catch (InterruptedException e) {e.printStackTrace();}}if (cnt++ % 2 == 0) {fruit = new Apple();System.out.println("父亲放了苹果");} else {fruit = new Oriange();System.out.println("父亲放了橘子");}"".notifyAll();}}}}// 消费者儿子class Child implements Runnable {private char gender;// 性别public Child(char gender) {super();this.gender = gender;}@Overridepublic void run() {while (true) {synchronized ("") {while (fruit == null || !(fruit instanceof Apple) && gender == '男'|| !(fruit instanceof Oriange) && gender == '女') {try {"".wait();} catch (InterruptedException e) {e.printStackTrace();}}if (gender == '男') {System.out.println("儿子吃了苹果");} else {System.out.println("女儿吃了橘子");}try {Thread.sleep(200);} catch (InterruptedException e) {e.printStackTrace();}fruit = null;"".notifyAll();}}}}public static void main(String[] args) {Test3 instance = new Test3();Thread parent = new Thread(instance.new Father());Thread son = new Thread(instance.new Child('男'));Thread daughter = new Thread(instance.new Child('女'));parent.start();son.start();daughter.start();}}
1 0
原创粉丝点击