import java.util.concurrent.locks.ReentrantLock;
/**
* ReentrantLock 測試用代碼
*
* @author TF12778 2019/10/21 15:30
*/
public class ReentrantLockTest extends Thread {
private static int count = 100000;// 10000000;
public static ReentrantLock lock = new ReentrantLock();
public static int i = 0;
public ReentrantLockTest(String name) {
super.setName(name);
}
/**
* 1。 當使用ReentrantLock鎖的時候,不論任何時候,輸出結果都是200000
* 2。 當不使用ReentrantLock鎖的時候,輸出結果可能不等於200000,剛剛測試了一把是199988
*/
@Override
public void run() {
for (int j = 0; j < count; j++) {
lock.lock();
try {
System.out.println(this.getName() + " " + i);
i++;
} finally {
lock.unlock();
}
}
}
/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
ReentrantLockTest test1 = new ReentrantLockTest("thread1");
ReentrantLockTest test2 = new ReentrantLockTest("thread2");
test1.start();
test2.start();
test1.join(); // 先執行子線程,再執行主線程
test2.join(); // 先執行子線程,再執行主線程
System.out.println("最後的執行結果:" + i); // 執行主線程
}
}