Object的锁使用

  • Post author:
  • Post category:其他


上一篇中用Condition实现了生产者和消费者,其中用到了Condition的await和singal,这个实现和Object的锁特别像,如果用Object的锁机制实现生产者和消费者,如下:

import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by lizhiqiang on 2016/12/23.
 */
public class testObjectLock2 {
    public static void main(String[] args){
        final BoundedBuffer buffer = new BoundedBuffer();
        ExecutorService service = Executors.newFixedThreadPool(2);

        service.execute(new Runnable() {
            @Override
            public void run() {
                while(true){
                    try {
                        Thread.currentThread().sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    buffer.put(1);
                }
            }
        });
        service.execute(new Runnable() {
            @Override
            public void run() {
                while(true) {
                    System.out.println(new Date() + ":" + buffer.take());
                }
            }
        });
        service.shutdown();
    }
    public static class BoundedBuffer{
        Object notEmpty = new Object();
        Object notFull = new Object();
        final Object[] items = new Object[3];
        int count;
        public BoundedBuffer(){
            count=0;
        }
        public void put(Object x){
            synchronized (notFull){
                if(count==2){
                    try {
                        notFull.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                synchronized (notEmpty){
                    ++count;
                    items[count] = x;
                    notEmpty.notify();
                }
            }
        }
        public Object take(){
            Object result;
            synchronized (notEmpty){
                if(count==0) {
                    try {
                        notEmpty.wait();

                    } catch (InterruptedException e) {
                    }
                }
                synchronized (notFull){
                    result = items[count--];
                    notFull.notify();
                }
                return result;
            }
        }
    }
}

执行结果:

Fri Dec 23 11:07:20 CST 2016:1

Fri Dec 23 11:07:21 CST 2016:1

Fri Dec 23 11:07:22 CST 2016:1

Fri Dec 23 11:07:23 CST 2016:1

Fri Dec 23 11:07:24 CST 2016:1

Fri Dec 23 11:07:25 CST 2016:1

Fri Dec 23 11:07:26 CST 2016:1

发现效果和上一篇一样。

下面开始讲两个问题:

1.用Condition或者Object怎么实现多消费者、多生产者?

2.Condition和Object到底有什么不同?

1.用Condition或者Object怎么实现多消费者、多生产者?

Condition实现:

import java.util.Date;



版权声明:本文为lizhiqiangxiaoda原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。