import java.util.concurrent.locks.ReentrantLock; /** * 解决多线程中线程安全问题方式三:调用Lock接口 1.因为Lock是接口,无法直接使用,所以使用Lock的实现类ReentrantLock 2.jdk5后新增的特性 3.lock需要手动调用lock()方法开启同步锁,当同步逻辑完成后,也需要手动调用unlock()方法来结束同步 */ public class LockDemo { public static void main(String[] args) { //实现方式 window1 w1 = new window1(); Thread t1 = new Thread(w1); Thread t2 = new Thread(w1); Thread t3 = new Thread(w1); t1.setName("Implement窗口1"); t2.setName("Implement窗口2"); t3.setName("Implement窗口3"); t1.start(); t2.start(); t3.start(); //继承方式 // window2 w = new window2(); // window2 w2 = new window2(); // window2 w3 = new window2(); // // w.setName("Extends窗口1"); // w2.setName("Extends窗口2"); // w3.setName("Extends窗口3"); // w.start(); // w2.start(); // w3.start(); } } /*实现方式*/ class window1 implements Runnable { private int num = 100; private ReentrantLock lock = new ReentrantLock(); // private ReentrantLock lock = new ReentrantLock(true); //代表公平锁,按照线程进入的先后顺序执行 @Override public void run() { while(true){ try { lock.lock(); if(num > 0){ System.out.println(Thread.currentThread().getName() + "卖票,票号为:" + num); num --; }else{ break; } }finally{ lock.unlock(); } } } } /*继承方式*/ class window2 extends Thread{ private static int num = 100; private static ReentrantLock lock = new ReentrantLock(); @Override public void run() { while(true){ try { lock.lock(); if(num > 0){ System.out.println(Thread.currentThread().getName() + "卖票,票号为:" + num); num--; }else{ break; } }finally{ lock.unlock(); } } } }
标签:Thread,lock,ReentrantLock,安全,num,window2,new,中线,多线程 From: https://www.cnblogs.com/sjzchf/p/17083253.html