论坛首页 编程语言技术论坛

多线程之ReentrantLock

浏览 1262 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2014-12-15  
<pre name="code" class="java">
package com.test2;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class Test2 {

public static void main(String[] args) throws InterruptedException { 
        final ExecutorService exec = Executors.newFixedThreadPool(4); 
        final ReentrantLock lock = new ReentrantLock(); 
        final Condition con = lock.newCondition(); 
        final int time = 5; 
        final Runnable add = new Runnable() { 
          public void run() { 
            System.out.println("Pre " + lock); 
            lock.lock(); 
            try { 
           
              con.await(time, TimeUnit.SECONDS); 
             
              //Thread.sleep(5000) ;
            } catch (InterruptedException e) { 
              e.printStackTrace(); 
            } finally { 
              System.out.println("Post " + lock.toString()); 
              lock.unlock(); 
            } 
          } 
        }; 
       
        /**
         * 开启测试线程:
         * 测试条件:四个线程占用同一把锁
         * 测试点:con.await与sleep的区别
         * 测试结果:await时
         * 这是它的输出:
Pre ReentrantLock@a59698[Unlocked]
Pre ReentrantLock@a59698[Unlocked]
Pre ReentrantLock@a59698[Unlocked]
Pre ReentrantLock@a59698[Unlocked]
Post ReentrantLock@a59698[Locked by thread pool-1-thread-1]
Post ReentrantLock@a59698[Locked by thread pool-1-thread-2]
Post ReentrantLock@a59698[Locked by thread pool-1-thread-3]
Post ReentrantLock@a59698[Locked by thread pool-1-thread-4]
每一个线程的锁状态都是“Unlocked”,所以都可以运行。但在把con.await改成Thread.sleep(5000)时,输出就变成了:
Pre ReentrantLock@a59698[Unlocked]
Pre ReentrantLock@a59698[Locked by thread pool-1-thread-1]
Pre ReentrantLock@a59698[Locked by thread pool-1-thread-1]
Pre ReentrantLock@a59698[Locked by thread pool-1-thread-1]
Post ReentrantLock@a59698[Locked by thread pool-1-thread-1]
Post ReentrantLock@a59698[Locked by thread pool-1-thread-2]
Post ReentrantLock@a59698[Locked by thread pool-1-thread-3]
Post ReentrantLock@a59698[Locked by thread pool-1-thread-4]
         * 测试结论: 线程在等待时(con.await),已经不在拥有(keep)该锁了,所以其他线程就可以获得重入锁了。
         */
        for(int index = 0; index &lt; 4; index++) {
        exec.submit(add); 
        }
        
        exec.shutdown(); 
      } 
}


</pre>
论坛首页 编程语言技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics