• 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();
         }
       } 
     }
    



  • 相关阅读:
    获取文件扩展名的几个函数
    Window下,在TEMP路径下生成一个临时文件名
    字符串中的TOUPPER函数
    字符串中的TRIM操作
    BIN转换成HEX格式及HEX转换成BIN的两个函数接口
    GMSSL在Window下的编译
    VS2012下自定义打开文件对话框
    Daliy Algorithm (graph,思维)-- day 59
    Daliy Algorithm (贪心,gcd)-- day 58
    图论--Floyd(弗洛伊德)算法
  • 原文地址:https://www.cnblogs.com/aukle/p/3233919.html
Copyright © 2020-2023  润新知