非公平锁 importjava.util.concurrent.locks.Lock; importjava.util.concurrent.locks.ReentrantLock; public class Demo3 { //隐式锁Lock public static void main(String[] args) { Runnable run = new ...
先上两段代码大家先看一下,经典的卖票问题,我们创建了三个子线程同时去操作一个变量

非公平锁

import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;publicclassDemo3{//隐式锁Lockpublicstaticvoidmain(String[] args){ Runnable run=newTickted();newThread(run).start();newThread(run).start();newThread(run).start();}staticclassTicktedimplementsRunnable{//总票数privateint count=10;//创建一把隐式锁//传入参数true表示公平锁private Lock l=newReentrantLock();@Overridepublicvoidrun(){while(true){//锁住 l.lock();if(count>0){ System.out.println("开始卖票");try{ Thread.sleep(1000);}catch(InterruptedException e){ e.printStackTrace();} count--; System.out.println(Thread.currentThread().getName()+"卖票成功 余票为:"+ count);}else{break;}//开锁 l.unlock();}}}}
结果:

公平锁

import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;publicclassDemo3{//隐式锁Lockpublicstaticvoidmain(String[] args){ Runnable run=newTickted();newThread(run).start();newThread(run).start();newThread(run).start();}staticclassTicktedimplementsRunnable{//总票数privateint count=10;//创建一把隐式锁//传入参数true表示公平锁private Lock l=newReentrantLock(true);@Overridepublicvoidrun(){while(true){//锁住 l.lock();if(count>0){ System.out.println("开始卖票");try{ Thread.sleep(1000);}catch(InterruptedException e){ e.printStackTrace();} count--; System.out.println(Thread.currentThread().getName()+"卖票成功 余票为:"+ count);}else{break;}//开锁 l.unlock();}}}}
结果: