验证lock锁是否时可重入锁
package com.yang.lock;
import java.util.concurrent.locks.ReentrantLock;
//验证Lock可重入锁
public class Demo06 {
public static void main(String[] args) {
ReentrantLock y = new ReentrantLock();//遥控器锁
ReentrantLock d = new ReentrantLock();//电池锁
Thread th = new Thread(new XiaoMing1(y,d));
Thread th1 = new Thread(new XiaoHong2(y,d));
th.start();
th1.start();
}
}
class XiaoMing1 implements Runnable{
private ReentrantLock ykq;
private ReentrantLock dc;
public XiaoMing1(ReentrantLock y, ReentrantLock d) {
this.ykq = y;
this.dc = d;
}
Lock锁
package com.yang.lock;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/*
Lock锁:
1] 多个线程使用时一定要保证同一个锁对象
2]lock.lock()加锁。lock.unlock()解锁。
3]如果代码出现了异常,程序不会自动解锁,所以使用Lock的时候 最好写到try catch finally代码中
*/
public class Demo05 {
public static void main(String[] args) {
//两个对象
Thread th = new Thread(new TicketTwo(),"窗口A");
Thread th1 = new Thread(new TicketTwo(),"窗口B");
th.start();
th1.start();
}
}
class TicketTwo implements Runnable {
static int num = 1;
static Lock lock = new ReentrantLock();//创建Lock锁 两个对象加一个static