本帖最后由 binghaiwang 于 2013-7-24 11:06 编辑
- import java.util.concurrent.locks.*;
- class ThreadTest
- {
- public static void main(String[] args)
- {
- Goods g = new Goods();
- g.set("商品");
- g.out();
- }
- }
- class Goods
- {
- private String name;
- private int count = 1;
- private boolean flag = false;
- private Lock lock = new ReentrantLock();
- private Condition con_p = lock.newCondition();
- private Condition con_c = lock.newCondition();
- public void set(final String name)
-
- {
-
- Runnable r = new Runnable()
- {
- public void run()
- {
- while (true)
- {
- lock.lock();
- try
- {
- while(flag)
- con_c.await();
- Goods.this.name = name+"--"+count++;
- System.out.println(Thread.currentThread().getName()+"..生产者.."+Goods.this.name);
- flag = true;
- con_p.signal();
- }
- catch (InterruptedException e)
- {
- }
-
- finally
- {
- lock.unlock();
- }
- }
- }
- };
- new Thread(r).start();
- }
- public void out()
- {
-
- Runnable r = new Runnable()
- {
- public void run()
- {
- while (true)
- {
- lock.lock();
- try
- {
- while(!flag)
- con_p.await();
-
- System.out.println(Thread.currentThread().getName()+"..........消费者.."+Goods.this.name);
- flag = false;
- con_c.signal();
- }
- catch (InterruptedException e)
- {
- }
-
- finally
- {
- lock.unlock();
- }
- }
- }
- };
- new Thread(r).start();
- new Thread(r).start();/*此处是自己试着看写上的,运行发现和普通写法{Thread t1 = new Thread(r) Thread t2 = new Thread(r) ,然后再各自start() }的 效果一样。 这里这样写是否正确,为什么参数是相同对象会建立不同的线程?*/
- }
- }
复制代码 |