本文共 1939 字,大约阅读时间需要 6 分钟。
不安全的代码
//测试Lock锁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 ticketNums = 10; //定义lock锁 private final ReentrantLock lock = new ReentrantLock(); @Override public void run() { while (true) { if (ticketNums > 0) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(ticketNums--); } else break; } }}
三个线程同时访问票,容易出现线程安全问题
运行结果代码
import java.util.concurrent.locks.ReentrantLock;//测试Lock锁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 ticketNums = 10; //定义lock锁 private final ReentrantLock lock = new ReentrantLock(); @Override public void run() { while (true){ //加锁 lock.lock(); try { if (ticketNums>0){ try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(ticketNums--); } else break; }finally { //解锁 lock.unlock(); } } }}
运行结果
转载地址:http://zseq.baihongyu.com/