Waiting on a condition in a reentrant lock

前端 未结 3 894
無奈伤痛
無奈伤痛 2021-02-01 16:02

The following code is taken from the JavaDoc of Condition:

class BoundedBuffer {
  final Lock lock = new ReentrantLock();
  final Condition notFull  = lock.newCo         


        
3条回答
  •  萌比男神i
    2021-02-01 16:36

    I tested below code with single monitor and below always performs better - Tested on 2 core machine, Condition performance is 10-15% below on an average

     final Object sync = new Object();
      AtomicInteger add=new AtomicInteger();
      AtomicInteger remove=new AtomicInteger();
       final Object[] items = new Object[1];
       int putptr, takeptr, count;        
    
     public void add(Object x) throws InterruptedException {
           add.incrementAndGet();
    
         synchronized (sync) {
    
           while (count == items.length)
             sync.wait();
           items[putptr] = x;
           if (++putptr == items.length) putptr = 0;
           ++count;
           sync.notify();
            }
       }
    
       public Object remove() throws InterruptedException {
           remove.incrementAndGet();
    
         synchronized (sync) {
    
           while (count == 0)
             sync.wait();
           Object x = items[takeptr];
           if (++takeptr == items.length) takeptr = 0;
           --count;
           sync.notify();
           return x;
    
           }
       }
    
    
      public static void main(String[] args) {
        final BoundedBuffer bf=new BoundedBuffer();
    
        Thread put =new Thread(){
            public void run(){
            try {
                while(true)
                bf.add(new Object());
            } catch (InterruptedException e) {
    
            }
            }
    
        };
        put.start();
    
        Thread take= new Thread(){
            public void run(){
            try {
            while(true)
                bf.remove();
            } catch (InterruptedException e) {
    
            }
            }
    
        };
        take.start();
    
        try {
            Thread.sleep(1000L);
            put.interrupt();
            take.interrupt();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    
    
        System.out.println("add:"+bf.add);
        System.out.println("remove:"+bf.remove);
    

提交回复
热议问题