黑马程序员技术交流社区
标题:
线程间通讯--1.5升级版的问题
[打印本页]
作者:
张盼
时间:
2014-5-18 22:00
标题:
线程间通讯--1.5升级版的问题
本帖最后由 张盼 于 2014-5-18 22:38 编辑
class Resource
{
private String name;
private int count = 1;
private boolean flag = false;
private Lock lock = new ReentrantLock();
private Condition condition =lock.newCondition();
public void set(String name)throws InterruptedException
{
lock.lock();
try
{
while(flag)
{
condition.await();
}
this.name = name+"---"+count++;
System.out.println(Thread.currentThread().getName()+" 生产者-- "+this.name);
flag = true;
condition.signal();
}
finally
{
lock.unlock();
}
}
public synchronized void out()
{
while(!flag)
{
try
{
this.wait();
}
catch(Exception e)
{
}
}
System.out.println(Thread.currentThread().getName()+" 消费者====== "+this.name);
flag = false;
this.notifyAll();
}
}
class Producer implements Runnable
{
private Resource res;
Producer(Resource res)
{
this.res = res;
}
public void run()
{
while(true)
{
res.set("+商品+");
}
}
}
class Consumer implements Runnable
{
private Resource res;
Consumer(Resource res)
{
this.res = res;
}
public void run()
{
while(true)
{
res.out();
}
}
}
class ProducerConsumerDemo2
{
public static void main(String[]args)
{
Resource r = new Resource();
Producer pro = new Producer(r);
Consumer con = new Consumer(r);
Thread t1 = new Thread(pro);
Thread t2 = new Thread(pro);
Thread t3 = new Thread(con);
Thread t4 = new Thread(con);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
这个程序哪里错了,为什么视频上这样写可以运行?
错误提示:
ProducerConsumerDemo2.java:7: 找不到符号
符号: 类 Lock
位置: 类 Resource
private Lock lock = new ReentrantLock();
^
ProducerConsumerDemo2.java:8: 找不到符号
符号: 类 Condition
位置: 类 Resource
private Condition condition =lock.newCondition();
^
ProducerConsumerDemo2.java:7: 找不到符号
符号: 类 ReentrantLock
位置: 类 Resource
private Lock lock = new ReentrantLock();
^
作者:
zhrnghgwsws
时间:
2014-5-18 22:14
你没有导包,需要import java.util.concurrent.locks.*;
作者:
张盼
时间:
2014-5-18 22:18
zhrnghgwsws 发表于 2014-5-18 22:14
你没有导包,需要import java.util.concurrent.locks.*;
非常感谢
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2