本帖最后由 刀郎去西藏 于 2015-12-29 23:39 编辑
我在跟着视频学习时,为什么我明明引入了"java.util.concurrent.locks.*",在程序中这句提示final Lock lock = new ReentrantLock();不兼容的类型。 ReentrantLock类不是实现了lock方法吗?这里不就是相当于父类引用指向子类对象,怎么能是不兼容的类型呢?望麻油门解答。- import java.util.concurrent.locks.*;
- //不引入这个类就总会报下面的不兼容错误。这是为什么呢?上面有通配符呀!!!!!
- import java.util.concurrent.locks.Lock;
- class Resource{
- private String name;
- private int num = 1;
- private boolean flag = false;
- //为什么会一直报不可兼容的类型???父类引用指向子类对象,怎么回事
- final Lock lock = new ReentrantLock();
- final Condition condition_pro = lock.newCondition();
- final Condition condition_con = lock.newCondition();
- public void set(String name)throws InterruptedException{
- lock.lock();
- try{
- while(flag){
- condition_pro.await();
- }
- this.name = name + "----" + num++;
- System.out.println("-------------------------"+Thread.currentThread().getName()+"我生产了"+this.name);
- condition_con.signal();
- flag = true;
-
- //catch(InterruptedException ie){}
- }finally{
- lock.unlock();
- }
- }
- public void out()throws InterruptedException{
- lock.lock();
- try{
- while(!flag){
- condition_con.await();
- }
- System.out.println(Thread.currentThread().getName()+"我消费了" + this.name);
- condition_pro.signal();
- flag = false;
- //catch(InterruptedException ie){}
- }finally{
- lock.unlock();
- }
- }
- }
- class Producer implements Runnable{
- private Resource r;
- Producer(Resource r){
- this.r = r;
- }
- public void run(){
- while(true){
- try{
- r.set("商品");
- }catch(InterruptedException ie){}
- }
- }
- }
- class Consumer implements Runnable{
- private Resource r;
- Consumer(Resource r){
- this.r = r;
- }
- public void run(){
- while(true){
- try{
- r.out();
- }catch(InterruptedException ie){}
- }
- }
- }
- public class ProducerConsumerTestImproved{
- public static void main(String[] args){
- Resource r = new Resource();
- Producer p = new Producer(r);
- Consumer c = new Consumer(r);
- Thread t1 = new Thread(p);
- Thread t2 = new Thread(p);
- Thread t3 = new Thread(c);
- Thread t4 = new Thread(c);
- t1.start();
- t2.start();
- t3.start();
- t4.start();
- }
- }
复制代码
|
|