本文共 1081 字,大约阅读时间需要 3 分钟。
这个加锁是显示定义的,比较简单,来看一下它怎么用
import java.util.concurrent.locks.ReentrantLock;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 ticketsnums = 10; //定义Lock锁 private final ReentrantLock lock = new ReentrantLock(); @Override public void run() { while (true){ try { //加锁 lock.lock(); if (ticketsnums > 0){ try { Thread.sleep(1000); System.out.println(ticketsnums--); } catch (InterruptedException e) { e.printStackTrace(); } }else { break; } }finally { //解锁 lock.unlock(); } } }}
可以看到确实比较简单,定义一个lock锁,用完的时候解锁就好,主要就是这个加锁解锁的过程放到 try-catch中就好
看到结果确实线程安全了
转载地址:http://guuef.baihongyu.com/