Watch the video of the learning process: [Crazy God Speaks Java]
https://www.bilibili.com/video/BV1V4411p7EF?p=3
Welcome everyone to support Oh, very conscientious teacher!
Introduction:
Unlocked code has concurrency issues
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;
}
}
}
}
Output result:
Locked code
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(); //解锁
}
}
}
}