本帖最后由 应广驰 于 2012-8-28 16:08 编辑
- package ygc;
- public class SuoDemo
- {
- public static void main(String[] args)
- {
- Resource r = new Resource();
- Put p = new Put(r);
- Out o = new Out(r);
- Thread t1 = new Thread(p,"生产1");
- Thread t2 = new Thread(p,"生产2");
- Thread t3 = new Thread(o,"消费");
-
- t1.start();
- t2.start();
- t3.start();
-
- }
- }
- class Resource
- {
- private String name;
- private int count = 1;
- private int x = 100;
- private boolean flag = false;
-
- public synchronized void set(String name)
- {
- while(x>0)
- {
- if(flag)
- {
- try
- {
- wait();
- }
- catch(Exception e){}
- }
- this.name = name + "-----" +count++;
- System.out.println(Thread.currentThread().getName()+this.name);
- flag = true;
- x--;
- this.notify();
- }
- }
- public synchronized void out()
- {
- while(x>0)
- {
- if(!flag)
- {
- try
- {
- wait();
- }
- catch(Exception e)
- {
- }
- }
- System.out.println(Thread.currentThread().getName()+this.name);
- flag = false;
- this.notify();
- }
- }
- }
- class Put implements Runnable
- {
- private Resource r;
- Put(Resource r)
- {
- this.r = r;
- }
- public void run()
- {
- r.set("物品");
- }
- }
- class Out implements Runnable
- {
- private Resource r;
- Out(Resource r)
- {
- this.r = r;
- }
- public void run()
- {
- r.out();
- }
- }
复制代码 生产2物品-----26
生产1物品-----27
消费物品-----27
为什么会出现这样的结果,一个Put的线程操作完不是应该out的线程操作,put的另一个线程因为锁上进不来么,怎么会put的线程操作了两次呢
在一个线程冻结的时候,另一个不是因为锁上无法操作了么
每次好像想到点子上了,头脑就自己绕浆糊了,思路又乱了,各位帮忙看一下 |