Java多线程4- Lock、Condition

来源:互联网 发布:linux ssh远程登录命令 编辑:程序博客网 时间:2024/04/29 01:23
        Lock是java.util.concurrent.locks包下的接口,Lock 实现提供了比使用synchronized 方法和语句可获得的更广泛的锁定操作,它能以更优雅的方式处理线程同步问题,我们拿Java线程(二)中的一个例子简单的实现一下和sychronized一样的效果,代码如下:

[java] view plaincopyprint?
  1. public class LockTest {  
  2.     public static void main(String[] args) {  
  3.         final Outputter1 output = new Outputter1();  
  4.         new Thread() {  
  5.             public void run() {  
  6.                 output.output("zhangsan");  
  7.             };  
  8.         }.start();        
  9.         new Thread() {  
  10.             public void run() {  
  11.                 output.output("lisi");  
  12.             };  
  13.         }.start();  
  14.     }  
  15. }  
  16. class Outputter1 {  
  17.     private Lock lock = new ReentrantLock();// 锁对象  
  18.     public void output(String name) {  
  19.         // TODO 线程输出方法  
  20.         lock.lock();// 得到锁  
  21.         try {  
  22.             for(int i = 0; i < name.length(); i++) {  
  23.                 System.out.print(name.charAt(i));  
  24.             }  
  25.         } finally {  
  26.             lock.unlock();// 释放锁  
  27.         }  
  28.     }  
  29. }  
        这样就实现了和sychronized一样的同步效果,需要注意的是,用sychronized修饰的方法或者语句块在代码执行完之后锁自动释放,而是用Lock需要我们手动释放锁,所以为了保证锁最终被释放(发生异常情况),要把互斥区放在try内,释放锁放在finally内。

        如果说这就是Lock,那么它不能成为同步问题更完美的处理方式,下面要介绍的是读写锁(ReadWriteLock),我们会有一种需求,在对数据进行读写的时候,为了保证数据的一致性和完整性,需要读和写是互斥的,写和写是互斥的,但是读和读是不需要互斥的,这样读和读不互斥性能更高些,来看一下不考虑互斥情况的代码原型:

[java] view plaincopyprint?
  1. public class ReadWriteLockTest {  
  2.     public static void main(String[] args) {  
  3.         final Data data = new Data();  
  4.         for (int i = 0; i < 3; i++) {  
  5.             new Thread(new Runnable() {  
  6.                 public void run() {  
  7.                     for (int j = 0; j < 5; j++) {  
  8.                         data.set(new Random().nextInt(30));  
  9.                     }  
  10.                 }  
  11.             }).start();  
  12.         }         
  13.         for (int i = 0; i < 3; i++) {  
  14.             new Thread(new Runnable() {  
  15.                 public void run() {  
  16.                     for (int j = 0; j < 5; j++) {  
  17.                         data.get();  
  18.                     }  
  19.                 }  
  20.             }).start();  
  21.         }  
  22.     }  
  23. }  
  24. class Data {      
  25.     private int data;// 共享数据      
  26.     public void set(int data) {  
  27.         System.out.println(Thread.currentThread().getName() + "准备写入数据");  
  28.         try {  
  29.             Thread.sleep(20);  
  30.         } catch (InterruptedException e) {  
  31.             e.printStackTrace();  
  32.         }  
  33.         this.data = data;  
  34.         System.out.println(Thread.currentThread().getName() + "写入" + this.data);  
  35.     }     
  36.     public void get() {  
  37.         System.out.println(Thread.currentThread().getName() + "准备读取数据");  
  38.         try {  
  39.             Thread.sleep(20);  
  40.         } catch (InterruptedException e) {  
  41.             e.printStackTrace();  
  42.         }  
  43.         System.out.println(Thread.currentThread().getName() + "读取" + this.data);  
  44.     }  
  45. }  
        部分输出结果:

[java] view plaincopyprint?
  1. Thread-1准备写入数据  
  2. Thread-3准备读取数据  
  3. Thread-2准备写入数据  
  4. Thread-0准备写入数据  
  5. Thread-4准备读取数据  
  6. Thread-5准备读取数据  
  7. Thread-2写入12  
  8. Thread-4读取12  
  9. Thread-5读取5  
  10. Thread-1写入12  
        我们要实现写入和写入互斥,读取和写入互斥,读取和读取互斥,在set和get方法加入sychronized修饰符:

[java] view plaincopyprint?
  1. public synchronized void set(int data) {...}      
  2. public synchronized void get() {...}  
        部分输出结果:
[java] view plaincopyprint?
  1. Thread-0准备写入数据  
  2. Thread-0写入9  
  3. Thread-5准备读取数据  
  4. Thread-5读取9  
  5. Thread-5准备读取数据  
  6. Thread-5读取9  
  7. Thread-5准备读取数据  
  8. Thread-5读取9  
  9. Thread-5准备读取数据  
  10. Thread-5读取9  
        我们发现,虽然写入和写入互斥了,读取和写入也互斥了,但是读取和读取之间也互斥了,不能并发执行,效率较低,用读写锁实现代码如下:

[java] view plaincopyprint?
  1. class Data {      
  2.     private int data;// 共享数据  
  3.     private ReadWriteLock rwl = new ReentrantReadWriteLock();     
  4.     public void set(int data) {  
  5.         rwl.writeLock().lock();// 取到写锁  
  6.         try {  
  7.             System.out.println(Thread.currentThread().getName() + "准备写入数据");  
  8.             try {  
  9.                 Thread.sleep(20);  
  10.             } catch (InterruptedException e) {  
  11.                 e.printStackTrace();  
  12.             }  
  13.             this.data = data;  
  14.             System.out.println(Thread.currentThread().getName() + "写入" + this.data);  
  15.         } finally {  
  16.             rwl.writeLock().unlock();// 释放写锁  
  17.         }  
  18.     }     
  19.     public void get() {  
  20.         rwl.readLock().lock();// 取到读锁  
  21.         try {  
  22.             System.out.println(Thread.currentThread().getName() + "准备读取数据");  
  23.             try {  
  24.                 Thread.sleep(20);  
  25.             } catch (InterruptedException e) {  
  26.                 e.printStackTrace();  
  27.             }  
  28.             System.out.println(Thread.currentThread().getName() + "读取" + this.data);  
  29.         } finally {  
  30.             rwl.readLock().unlock();// 释放读锁  
  31.         }  
  32.     }  
  33. }  

        部分输出结果:

[java] view plaincopyprint?
  1. Thread-4准备读取数据  
  2. Thread-3准备读取数据  
  3. Thread-5准备读取数据  
  4. Thread-5读取18  
  5. Thread-4读取18  
  6. Thread-3读取18  
  7. Thread-2准备写入数据  
  8. Thread-2写入6  
  9. Thread-2准备写入数据  
  10. Thread-2写入10  
  11. Thread-1准备写入数据  
  12. Thread-1写入22  
  13. Thread-5准备读取数据  

        从结果可以看出实现了我们的需求,这只是锁的基本用法,锁的机制还需要继续深入学习。

       Condition

       Condition 将 Object 监视器方法(wait、notify 和 notifyAll)分解成截然不同的对象,以便通过将这些对象与任意 Lock 实现组合使用,为每个对象提供多个等待 set (wait-set)。其中,Lock 替代了 synchronized 方法和语句的使用,Condition 替代了 Object 监视器方法的使用。下面将之前写过的一个线程通信的例子替换成用Condition实现,代码如下:

[java] view plaincopyprint?
  1. public class ThreadTest2 {  
  2.     public static void main(String[] args) {  
  3.         final Business business = new Business();  
  4.         new Thread(new Runnable() {  
  5.             @Override  
  6.             public void run() {  
  7.                 threadExecute(business, "sub");  
  8.             }  
  9.         }).start();  
  10.         threadExecute(business, "main");  
  11.     }     
  12.     public static void threadExecute(Business business, String threadType) {  
  13.         for(int i = 0; i < 100; i++) {  
  14.             try {  
  15.                 if("main".equals(threadType)) {  
  16.                     business.main(i);  
  17.                 } else {  
  18.                     business.sub(i);  
  19.                 }  
  20.             } catch (InterruptedException e) {  
  21.                 e.printStackTrace();  
  22.             }  
  23.         }  
  24.     }  
  25. }  
  26. class Business {  
  27.     private boolean bool = true;  
  28.     private Lock lock = new ReentrantLock();  
  29.     private Condition condition = lock.newCondition();   
  30.     public /*synchronized*/ void main(int loop) throws InterruptedException {  
  31.         lock.lock();  
  32.         try {  
  33.             while(bool) {                 
  34.                 condition.await();//this.wait();  
  35.             }  
  36.             for(int i = 0; i < 100; i++) {  
  37.                 System.out.println("main thread seq of " + i + ", loop of " + loop);  
  38.             }  
  39.             bool = true;  
  40.             condition.signal();//this.notify();  
  41.         } finally {  
  42.             lock.unlock();  
  43.         }  
  44.     }     
  45.     public /*synchronized*/ void sub(int loop) throws InterruptedException {  
  46.         lock.lock();  
  47.         try {  
  48.             while(!bool) {  
  49.                 condition.await();//this.wait();  
  50.             }  
  51.             for(int i = 0; i < 10; i++) {  
  52.                 System.out.println("sub thread seq of " + i + ", loop of " + loop);  
  53.             }  
  54.             bool = false;  
  55.             condition.signal();//this.notify();  
  56.         } finally {  
  57.             lock.unlock();  
  58.         }  
  59.     }  
  60. }  

        在Condition中,用await()替换wait(),用signal()替换notify(),用signalAll()替换notifyAll(),传统线程的通信方式,Condition都可以实现,这里注意,Condition是被绑定到Lock上的,要创建一个Lock的Condition必须用newCondition()方法。

        这样看来,Condition和传统的线程通信没什么区别,Condition的强大之处在于它可以为多个线程间建立不同的Condition,下面引入API中的一段代码,加以说明。

[java] view plaincopyprint?
  1. class BoundedBuffer {  
  2.    final Lock lock = new ReentrantLock();//锁对象  
  3.    final Condition notFull  = lock.newCondition();//写线程条件   
  4.    final Condition notEmpty = lock.newCondition();//读线程条件   
  5.   
  6.    final Object[] items = new Object[100];//缓存队列  
  7.    int putptr/*写索引*/, takeptr/*读索引*/, count/*队列中存在的数据个数*/;  
  8.   
  9.    public void put(Object x) throws InterruptedException {  
  10.      lock.lock();  
  11.      try {  
  12.        while (count == items.length)//如果队列满了   
  13.          notFull.await();//阻塞写线程  
  14.        items[putptr] = x;//赋值   
  15.        if (++putptr == items.length) putptr = 0;//如果写索引写到队列的最后一个位置了,那么置为0  
  16.        ++count;//个数++  
  17.        notEmpty.signal();//唤醒读线程  
  18.      } finally {  
  19.        lock.unlock();  
  20.      }  
  21.    }  
  22.   
  23.    public Object take() throws InterruptedException {  
  24.      lock.lock();  
  25.      try {  
  26.        while (count == 0)//如果队列为空  
  27.          notEmpty.await();//阻塞读线程  
  28.        Object x = items[takeptr];//取值   
  29.        if (++takeptr == items.length) takeptr = 0;//如果读索引读到队列的最后一个位置了,那么置为0  
  30.        --count;//个数--  
  31.        notFull.signal();//唤醒写线程  
  32.        return x;  
  33.      } finally {  
  34.        lock.unlock();  
  35.      }  
  36.    }   
  37.  }  

        这是一个处于多线程工作环境下的缓存区,缓存区提供了两个方法,put和take,put是存数据,take是取数据,内部有个缓存队列,具体变量和方法说明见代码,这个缓存区类实现的功能:有多个线程往里面存数据和从里面取数据,其缓存队列(先进先出后进后出)能缓存的最大数值是100,多个线程间是互斥的,当缓存队列中存储的值达到100时,将写线程阻塞,并唤醒读线程,当缓存队列中存储的值为0时,将读线程阻塞,并唤醒写线程,下面分析一下代码的执行过程:

        1. 一个写线程执行,调用put方法;

        2. 判断count是否为100,显然没有100;

        3. 继续执行,存入值;

        4. 判断当前写入的索引位置++后,是否和100相等,相等将写入索引值变为0,并将count+1;

        5. 仅唤醒读线程阻塞队列中的一个;

        6. 一个读线程执行,调用take方法;

        7. ……

        8. 仅唤醒写线程阻塞队列中的一个。

        这就是多个Condition的强大之处,假设缓存队列中已经存满,那么阻塞的肯定是写线程,唤醒的肯定是读线程,相反,阻塞的肯定是读线程,唤醒的肯定是写线程,那么假设只有一个Condition会有什么效果呢,缓存队列中已经存满,这个Lock不知道唤醒的是读线程还是写线程了,如果唤醒的是读线程,皆大欢喜,如果唤醒的是写线程,那么线程刚被唤醒,又被阻塞了,这时又去唤醒,这样就浪费了很多时间。

 

原创粉丝点击