這是自JDK5.0開始提供的Java並發包裡面的類
下面是關於Java並發鎖的測試代碼
- package com.jadyer.thread.lock;
-
- import java.util.concurrent.locks.Lock;
- import java.util.concurrent.locks.ReentrantLock;
-
- /**
- * LockTest
- * @author 宏宇
- * @create Mar 1, 2012 7:12:04 PM
- */
- public class LockTest {
- public static void main(String[] args) {
- FoodCenter fc = new FoodCenter();
- new Thread(new ThreadDog(fc, "It is dog`s food")).start();
- new Thread(new ThreadPig(fc, "It is pig`s food")).start();
- }
- }
-
-
- class ThreadDog implements Runnable{
- private FoodCenter fc;
- private String foodname;
- public ThreadDog(FoodCenter fc, String foodname){
- this.fc = fc;
- this.foodname = foodname;
- }
- @Override
- public void run() {
- while(true){
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- fc.getFood(foodname);
- }
- }
- }
-
-
- class ThreadPig implements Runnable{
- private FoodCenter fc;
- private String foodname;
- public ThreadPig(FoodCenter fc, String foodname){
- this.fc = fc;
- this.foodname = foodname;
- }
- @Override
- public void run() {
- while(true){
- try {
- Thread.sleep(2000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- fc.getFood(foodname);
- }
- }
- }
-
-
- /**
- * @see =========================================================================================
- * @see java.util.concurrent是JDK5.0開始提供的Java並發包,其子包locks是專門用於處理線程鎖的
- * @see java.util.concurrent.locks.Lock較synchronized關鍵字比,有一個最大的區別,那就是
- * @see Lock可以比synchronized更細粒度的控制鎖,體現在try{...}finally{mylock.unlock();}
- * @see =========================================================================================
- * @see Lock有點像公共廁所的門闩,只有正在使用廁所的人,把門闩打開出來了,其它人才可以使用公廁
- * @see Lock比傳統線程模型中的synchronized方式更加面向對象。與生活中的鎖類似,鎖本身也應該是一個對象
- * @see 兩個線程執行的代碼片段要實現同步互斥的效果,那麼這兩個線程所使用的必須是同一個Lock對象
- * @see 並且,鎖應該位於待操作��資源類的內部方法中,而非線程代碼中
- * @see =========================================================================================
- */
- class FoodCenter {
- Lock mylock = new ReentrantLock(); //創建一個鎖
- public void getFood(String name) {
- int len = name.length();
- mylock.lock(); //上鎖
- try {
- for (int i = 0; i < len; i++) {
- System.out.print(name.charAt(i));
- }
- System.out.println();
- } finally {
- mylock.unlock(); //解鎖
- }
- }
- }