public class MakerAndSaler { public static void main(String[] args) { HMaker maker = new HMaker(); Hseller seller = new Hseller(); maker.start(); seller.start(); } } class box { static Object obj = new Object(); static int sale = 0; static int production = 5; static int totalMaterial = 10; } class HMaker extends Thread { // box myBox = new box(); public void make() { synchronized (box.obj) { box.production++; box.obj.notify(); } } public void run() { while (box.production < box.totalMaterial) { if (box.production > 0) { { System.out.println("厨师:" + "汉堡包来了(总共)" + (box.production - box.sale) + "个"); } } try { sleep(5000); } catch (Exception e) { } make(); } } } class Hseller extends Thread { public void sell() { if (box.production == 0) { System.out.println("营业员:顾客朋友们,请稍等一下,汉堡包没了"); } try { box.obj.wait(); } catch (Exception e) { } box.sale++; System.out.println("营业员:顾客好,汉堡包上来了,(总共卖了" + box.sale + "个"); } /* * public void sell() { synchronized (box.obj) { if (box.production == 0) { * System.out.println("营业员:顾客朋友们,请稍等一下,汉堡包没了"); } try { box.obj.wait(); } * catch (Exception e) { * * } box.production++; System.out.println("营业员:顾客好,汉堡包上来了,(总共卖了" + box.sale * + "个"); } } */ public void run() { while (box.production > box.sale) { try { sleep(1000); } catch (Exception e) { } sell(); } } }public class MakerAndSaler { public static void main(String[] args) { HMaker maker = new HMaker(); Hseller seller = new Hseller(); maker.start(); seller.start(); } } class box { static Object obj = new Object(); static int sale = 0; static int production = 5; static int totalMaterial = 10; } class HMaker extends Thread { // box myBox = new box(); public void make() { synchronized (box.obj) { box.production++; box.obj.notify(); } } public void run() { while (box.production < box.totalMaterial) { if (box.production > 0) { { System.out.println("厨师:" + "汉堡包来了(总共)" + (box.production - box.sale) + "个"); } } try { sleep(5000); } catch (Exception e) { } make(); } } } class Hseller extends Thread { public void sell() { if (box.production == 0) { System.out.println("营业员:顾客朋友们,请稍等一下,汉堡包没了"); } try { box.obj.wait(); } catch (Exception e) { } box.sale++; System.out.println("营业员:顾客好,汉堡包上来了,(总共卖了" + box.sale + "个"); } /* * public void sell() { synchronized (box.obj) { if (box.production == 0) { * System.out.println("营业员:顾客朋友们,请稍等一下,汉堡包没了"); } try { box.obj.wait(); } * catch (Exception e) { * * } box.production++; System.out.println("营业员:顾客好,汉堡包上来了,(总共卖了" + box.sale * + "个"); } } */ public void run() { while (box.production > box.sale) { try { sleep(1000); } catch (Exception e) { } sell(); } } }
相关分类