本帖最后由 李征雪 于 2012-4-6 15:58 编辑
- //Demo1205.java
- class Commodity//商品类
- {
- private String name;
- private int count = 1;
- private boolean flag = false;
- public synchronized void Input(String name)
- {
- this.name = name +"... ..."+count++;
- while(true)
- {
- while (flag)
- {
- try
- {
- wait();
- }
- catch (Exception e)
- {
- }
- System.out.println(Thread.currentThread().getName()+"生产-->"+name);
- flag = !flag;
- notifyAll();
- }
- }
- }
- public synchronized void Output()
- {
- while(true)
- {
- while (!flag)
- {
- try
- {
- wait();
- }
- catch (Exception e)
- {
- }
- System.out.println(Thread.currentThread().getName()+"消费------>"+name);
- flag = !flag;
- notifyAll();
- }
- }
- }
- }
- class PersonInput implements Runnable//生产类
- {
- Commodity com;
- PersonInput(Commodity com)
- {
- this.com = com;
- }
- public void run()
- {
- com.Input("商品");
- }
- }
- class PersonOutput implements Runnable//消费类
- {
- Commodity com;
- PersonOutput(Commodity com)
- {
- this.com = com;
- }
- public void run()
- {
- com.Output();
- }
- }
- class Demo1205
- {
- public static void main(String[] args)
- {
- Commodity com = new Commodity();
- PersonInput pi = new PersonInput(com);
- PersonOutput po = new PersonOutput(com);
- Thread t1 = new Thread(pi);
- Thread t2 = new Thread(po);
- t1.start();
- t2.start();
- // System.out.println("Hello World!");
- }
- }
复制代码 学习毕老师第12天课程写的这段代码,弄了两个小时了,老是一大堆错,现在不报错了,但是没有运行结果,朋友们帮我看看哪里出问题了。 |