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://i-blog.csdnimg.cn/blog_migrate/588ccf9a5ffe2bc86615ecb8d2403c6a.png)
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://i-blog.csdnimg.cn/blog_migrate/8da4d0cf4785e4e261cfae4c2f5cbf6d.png)
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://i-blog.csdnimg.cn/blog_migrate/552d30383c6669e16b20fcd28888bfde.png)
非公平锁
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/bf1f091423aa3216cba04f2b86fea1cc.png)