調用lock()方法獲得鎖, 調用unlock()釋放鎖。
package com.wkcto.lock.reentrant;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* Lock鎖的基本使用
*/
public class Test02 {
//定義顯示鎖
static Lock lock = new ReentrantLock();
//定義方法
public static void sm(){
//先獲得鎖
lock.lock();
//for循環就是同步代碼塊
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName() + " -- " + i);
}
//釋放鎖
lock.unlock();
}
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
sm();
}
};
//啟動三個線程
new Thread(r).start();
new Thread(r).start();
new Thread(r).start();
}
}
package com.wkcto.lock.reentrant;
import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* 使用Lock鎖同步不同方法中的同步代碼塊
*/
public class Test03 {
static Lock lock = new ReentrantLock(); //定義鎖對象
public static void sm1(){
//經常在try代碼塊中獲得Lock鎖, 在finally子句中釋放鎖
try {
lock.lock(); //獲得鎖
System.out.println(Thread.currentThread().getName() + "-- method 1 -- " + System.currentTimeMillis() );
Thread.sleep(new Random().nextInt(1000));
System.out.println(Thread.currentThread().getName() + "-- method 1 -- " + System.currentTimeMillis() );
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock(); //釋放鎖
}
}
public static void sm2(){
try {
lock.lock(); //獲得鎖
System.out.println(Thread.currentThread().getName() + "-- method 22 -- " + System.currentTimeMillis() );
Thread.sleep(new Random().nextInt(1000));
System.out.println(Thread.currentThread().getName() + "-- method 22 -- " + System.currentTimeMillis() );
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock(); //釋放鎖
}
}
public static void main(String[] args) {
Runnable r1 = new Runnable() {
@Override
public void run() {
sm1();
}
};
Runnable r2 = new Runnable() {
@Override
public void run() {
sm2();
}
};
new Thread(r1).start();
new Thread(r1).start();
new Thread(r1).start();
new Thread(r2).start();
new Thread(r2).start();
new Thread(r2).start();
}
}