Lock和Condition的使用

这个例子解释lock, Condition, while()控制的使用

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class LockCoditionText {

	    final Business business = new Business();

	    public static void main(String[] args) {
	        new LockCoditionText().init();
	    }

	    private void init() {

	        new Thread(new Runnable() {

	            @Override
	            public void run() {
	                for (int i = 0; i <= 50; i++) {
	                    business.sub(i);//(1)调用sub方法并将bShuldSub置为false
	                }
	            }
	        }).start();

	        for (int i = 0; i <= 50; i++) {
	            business.main(i);
	        }

	    }

	    class Business {
	        private boolean bShouldSub = true;
	        Lock lock = new ReentrantLock();
	        Condition condition = lock.newCondition();

	        public void sub(int i) {
	        	//加锁,此线程不能被其他线程打断
	        	lock.lock();
	            try {
	            	//如果bShowldSub为false, 进入等待
	                while (!bShouldSub) {
	                    condition.await();
	                }

	                for (int j = 1; j <= 10; j++) {

	                    System.out.println("sub thread sequence of" + j
	                            + ",loop of " + i);
	                }
	                //以后main方法中可以执行
	                bShouldSub = false;
	                condition.signal();
	            } catch (Exception e) {

	                e.printStackTrace();

	            } finally {
	            	//解锁,此线程结束
	                lock.unlock();
	            }
	        }

	        public synchronized void main(int i) {
	        	//加锁
	            lock.lock();
	            try {
	                while (bShouldSub) {
	                    condition.await();
	                }

	                for (int j = 1; j <= 10; j++) {

	                    System.out.println("main thread sequence of" + j
	                            + ",loop of " + i);
	                }
	                //使sub方法可以执行
	                bShouldSub = true;
	                condition.signal();
	            } catch (InterruptedException e) {
	                e.printStackTrace();
	            } finally {
	            	//解锁
	                lock.unlock();
	            }
	        }

	    }
}


API文档上例子如下:

class BoundedBuffer { 
   final Lock lock = new ReentrantLock(); 
   //下面使用两个condition可以使用put控制take的执行 
   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(); 
     } 
   } 

ArrayBlockingQueue类提供了这项功能


三个条件多路通信  老大通知老二,老二通知老三,老三通知老大

package cn.edu.zzuli;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockCoditionText {
    final Business business = new Business();

    public static void main(String[] args) {
        new LockCoditionText().init();
    }

    private void init() {

        new Thread(new Runnable() {

            @Override
            public void run() {
                for (int i = 0; i <= 50; i++) {
                    business.sub2(i);
                }
            }
        }).start();

        new Thread(new Runnable() {

            @Override
            public void run() {
                for (int i = 0; i <= 50; i++) {
                    business.sub3(i);
                }
            }
        }).start();
        
        for (int i = 0; i <= 50; i++) {
            business.main(i);
        }

    }

    class Business {
        private int flag = 1;
        Lock lock = new ReentrantLock();
        Condition condition1 = lock.newCondition();
        Condition condition2= lock.newCondition();
        Condition condition3= lock.newCondition();
        public void sub2(int i) {
            lock.lock();
            try {
                while (flag!=2) {
                    condition2.await();
                }

                for (int j = 1; j <= 10; j++) {

                    System.out.println("sub2 thread sequence of" + j
                            + ",loop of " + i);
                }
                flag = 3;
                condition3.signal();
            } catch (Exception e) {

                e.printStackTrace();

            } finally {
                lock.unlock();
            }
        }

        public void sub3(int i) {
            lock.lock();
            try {
                while (flag!=3) {
                    condition3.await();
                }

                for (int j = 1; j <= 10; j++) {

                    System.out.println("sub3 thread sequence of" + j
                            + ",loop of " + i);
                }
                flag =1;
                condition1.signal();
            } catch (Exception e) {

                e.printStackTrace();

            } finally {
                lock.unlock();
            }
        }
        
        public synchronized void main(int i) {
            lock.lock();
            try {
                while (flag!=1) {
                    condition1.await();
                }

                for (int j = 1; j <= 20; j++) {

                    System.out.println("main thread sequence of" + j
                            + ",loop of " + i);
                }
                flag = 2;
                condition2.signal();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }

    }

}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值