Lock锁
作者:互联网
lock
验证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;
}
@Override
public void run() {
ykq.lock();
System.out.println("小明强到遥控器壳");
if (dc.isLocked()) {//判断是否有锁
ykq.unlock();
}
dc.lock();
System.out.println("小明强到电池");
dc.unlock();
if (ykq.isLocked()){//有锁就解锁
ykq.unlock();
}
}
}
class XiaoHong2 implements Runnable{
private ReentrantLock ykq;
private ReentrantLock dc;
public XiaoHong2(ReentrantLock y, ReentrantLock d) {
this.ykq = y;
this.dc = d;
}
@Override
public void run() {
dc.lock();
System.out.println("小红强到遥控器壳");
ykq.lock();
System.out.println("小红强到电池");
ykq.unlock();
dc.unlock();
}
}
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
@Override
public void run() {
while (num<=100){
lock.lock();
try {
if (num <= 100) {
System.out.println(Thread.currentThread().getName() + "卖了票" + num + "张票");
num++;
} else {
System.out.println("票已经卖完了");
}
//int a = 10/0;//异常
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();//将unLock放入finally中,有异常后,也可以将锁给释放
}
}
}
}
标签:Thread,Lock,ReentrantLock,dc,ykq,lock,new 来源: https://www.cnblogs.com/yzlworld/p/16324784.html