欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

java,

来源: javaer 分享于  点击 19728 次 点评:181

java,


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();}}

相关文章

    暂无相关文章
相关栏目:

用户点评