学习过程观看视频:[狂神说Java]
https://www.bilibili.com/video/BV1V4411p7EF?p=3
欢迎大家支持噢,很良心的老师了!
简介:
未加锁的代码存在并发问题
package com.zjl;
/**
* Created by zjl
* 2020/11/18
**/
public class TestLock {
public static void main(String[] args) {
TestLock2 testLock2 = new TestLock2();
new Thread(testLock2,"学生").start();
new Thread(testLock2,"老师").start();
new Thread(testLock2,"黄牛党").start();
}
}
class TestLock2 implements Runnable{
int ticketsNum = 10;
@Override
public void run() {
while (true){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(ticketsNum > 0){
System.out.println(Thread.currentThread().getName() + "买到了第" + ticketsNum-- +"张票");
}else {
break;
}
}
}
}
输出结果:
加锁后的代码
package com.zjl;
import java.util.concurrent.locks.ReentrantLock;
/**
* Created by zjl
* 2020/11/18
**/
public class TestLock {
public static void main(String[] args) {
TestLock2 testLock2 = new TestLock2();
new Thread(testLock2,"学生").start();
new Thread(testLock2,"老师").start();
new Thread(testLock2,"黄牛党").start();
}
}
class TestLock2 implements Runnable{
int ticketsNum = 10;
//定义一个锁
private final ReentrantLock reentrantLock = new ReentrantLock();
@Override
public void run() {
while (true){
try {
reentrantLock.lock(); //加锁
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(ticketsNum > 0){
System.out.println(Thread.currentThread().getName() + "买到了第" + ticketsNum-- +"张票");
}else {
break;
}
}finally {
reentrantLock.unlock(); //解锁
}
}
}
}