zoukankan      html  css  js  c++  java
  • JDK1.5中LOCK,Condition的使用

    import java.util.concurrent.locks.Condition;
    import java.util.concurrent.locks.Lock;
    import java.util.concurrent.locks.ReentrantLock;


    public class LockTest10050 {
    public static void main(String[] args) {
    final Bussiness bussiness = new Bussiness();


    new Thread(new Runnable() {
    public void run() {
    for (int i = 1; i < 51; i++) {
    bussiness.sub(i);
    }
    }
    }).start();


    new Thread(new Runnable() {
    public void run() {
    for (int i = 1; i < 51; i++) {
    bussiness.main(i);
    }
    }
    }).start();
    }
    }


    class Bussiness {
    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();
    boolean flag = true;


    public void sub(int i) {
    lock.lock();
    try {
    while (!flag)
    condition.await();
    for (int j = 1; j < 11; j++) {
    System.out.println("子线程第" + i + "次循环: 次数为" + j);
    }
    flag = false;
    condition.signal();
    } catch (InterruptedException e) {
    e.printStackTrace();
    } finally {
    lock.unlock();
    }
    }


    public void main(int i) {
    lock.lock();
    try {
    while (flag)
    condition.await();
    for (int j = 1; j < 101; j++) {
    System.out.println("主线程第" + i + "次循环: 次数为" + j);
    }
    flag = true;
    condition.signal();
    } catch (InterruptedException e) {
    e.printStackTrace();
    } finally {
    lock.unlock();
    }
    }

    }


    API文档中实例代码:

    class BoundedBuffer {
       final Lock lock = new ReentrantLock();
       final Condition notFull  = lock.newCondition(); 
       final Condition notEmpty = lock.newCondition(); 
    
       final Object[] items = new Object[100];
       int putptr, takeptr, count;
    
       public void put(Object x) throws InterruptedException {
         lock.lock();
         try {
           while (count == items.length) 
             notFull.await();
           items[putptr] = x; 
           if (++putptr == items.length) putptr = 0;
           ++count;
           notEmpty.signal();
         } finally {
           lock.unlock();
         }
       }
    
       public Object take() throws InterruptedException {
         lock.lock();
         try {
           while (count == 0) 
             notEmpty.await();
           Object x = items[takeptr]; 
           if (++takeptr == items.length) takeptr = 0;
           --count;
           notFull.signal();
           return x;
         } finally {
           lock.unlock();
         }
       } 
     }
    



  • 相关阅读:
    Vue单向数据流
    npm常用命令
    vue自定义指令
    slot的用法(Vue插槽)
    js闭包
    canvas 给画的多边形着色
    canvas画线
    canvas初体验
    canvas
    json
  • 原文地址:https://www.cnblogs.com/aukle/p/3233919.html
Copyright © 2011-2022 走看看