1、未用锁情况
public static void main(String[] args) {
TestTicket testTicket = new TestTicket();
Thread threadA = new Thread(testTicket);
Thread threadB = new Thread(testTicket);
Thread threadC = new Thread(testTicket);
Thread threadD = new Thread(testTicket);
Thread threadE = new Thread(testTicket);
threadA.start();
threadB.start();
threadC.start();
threadD.start();
threadE.start();
}
public static class TestTicket implements Runnable {
private Integer num = 200;
@Override
public void run() {
while (true) {
try {Thread.sleep(10);} catch (Exception e) {}
if (num > 0) {
System.out.println("当前线程名字:" + Thread.currentThread().getName() + ";剩余" + num--);
}
}
}
}
- 结果(存在线程安全问题)
![在这里插入图片描述](https://img-blog.csdnimg.cn/11432f280e8840c8bbed1ba1d735114b.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA5p2OX-adsA==,size_20,color_FFFFFF,t_70,g_se,x_16)
2、使用synchronized
public class TestSynchronized {
public static void main(String[] args) {
TestTicket testTicket = new TestTicket();
Thread threadA = new Thread(testTicket);
Thread threadB = new Thread(testTicket);
Thread threadC = new Thread(testTicket);
Thread threadD = new Thread(testTicket);
Thread threadE = new Thread(testTicket);
threadA.start();
threadB.start();
threadC.start();
threadD.start();
threadE.start();
}
public static class TestTicket implements Runnable {
private Integer num = 200;
@Override
public void run() {
while (true) {
synchronized (this) {
try {Thread.sleep(10);} catch (Exception e) {}
if (num > 0) {
System.out.println("当前线程名字:" + Thread.currentThread().getName() + ";剩余" + num--);
}
}
}
}
}
}
- 结果(解决了线程安全问题)
![在这里插入图片描述](https://img-blog.csdnimg.cn/940a1d80e95544fa884501090809f27b.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA5p2OX-adsA==,size_20,color_FFFFFF,t_70,g_se,x_16)
3、使用ReentrantLock
public static void main(String[] args) {
TestTicket testTicket = new TestTicket();
Thread threadA = new Thread(testTicket);
Thread threadB = new Thread(testTicket);
Thread threadC = new Thread(testTicket);
Thread threadD = new Thread(testTicket);
Thread threadE = new Thread(testTicket);
threadA.start();
threadB.start();
threadC.start();
threadD.start();
threadE.start();
}
public static class TestTicket implements Runnable {
private Integer num = 200;
ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
while (true) {
try {
lock.lock();
try {Thread.sleep(100);} catch (Exception e) {}
if (num > 0) {
System.out.println("当前线程名字:" + Thread.currentThread().getName() + ";剩余" + num--);
}
}finally {
lock.unlock();
}
}
}
}
公平锁
![在这里插入图片描述](https://img-blog.csdnimg.cn/1ecdf07f73404657b2603642ccb3f078.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA5p2OX-adsA==,size_20,color_FFFFFF,t_70,g_se,x_16)
非公平锁
![在这里插入图片描述](https://img-blog.csdnimg.cn/a59f18c19d17444e96cb6c2484280af9.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA5p2OX-adsA==,size_20,color_FFFFFF,t_70,g_se,x_16)