package com.xue.ssm;public class Ck { public static void main(String[] args) { Ck ck = new Ck(); Thread sc = new Thread(new Sc(ck)); Thread xf = new Thread(new Xf(ck)); sc.start(); xf.start(); } private char[] rb = new char[10]; int wp = 0 ; public synchronized void shengchan(char aa){ //如果物品装满仓库,就等待 while(wp == rb.length){ try { this.wait(); }catch (Exception e){} } this.notify();//唤醒另一个消费线程,消费 rb[wp] = aa; ++wp; System.out.println("生产线程生产第"+wp+"个物品,产品是:"+aa); } public synchronized void xiaofei(){ char aa; //如果仓库为0,就等待让其生产 while (wp == 0){ try { this.wait(); } catch (Exception e) { e.printStackTrace(); } } this.notify();//唤醒另一个线程 aa = rb[wp-1]; System.out.println("消费第"+wp+"个物品,名字是"+aa); --wp; }}class Sc implements Runnable{ private Ck ck = null; public Sc(Ck ck ){ this.ck = ck; } @Override public void run() { char aa; for(int i = 0 ;i<26 ;i++){ aa = (char)('A'+i); ck.shengchan(aa); } }}class Xf implements Runnable{ private Ck ck = null; public Xf(Ck ck ){ this.ck = ck; } @Override public void run() { for(int i = 0 ;i<26 ;i++){ ck.xiaofei(); } }}
|
|