可重入锁的用法
package lock.reentrantlock;import java.util.concurrent.locks.ReentrantLock;/*** 描述: 演示多線程預定電影院座位*/
public class CinemaBookSeat {private static ReentrantLock lock = new ReentrantLock();private static void bookSeat() {lock.lock();try {System.out.println(Thread.currentThread().getName() + "開始預定座位");Thread.sleep(1000);System.out.println(Thread.currentThread().getName() + "完成預定座位");} catch (InterruptedException e) {e.printStackTrace();} finally {lock.unlock();}}public static void main(String[] args) {new Thread(() -> bookSeat()).start();new Thread(() -> bookSeat()).start();new Thread(() -> bookSeat()).start();new Thread(() -> bookSeat()).start();}
}
package lock.reentrantlock;import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;/*** 描述: 演示ReentrantLock的基本用法,演示被打斷*/
public class LockDemo {public static void main(String[] args) {new LockDemo().init();}private void init() {final Outputer outputer = new Outputer();new Thread(new Runnable() {@Overridepublic void run() {while (true) {try {Thread.sleep(5);} catch (InterruptedException e) {e.printStackTrace();}outputer.output("悟空");}}}).start();new Thread(new Runnable() {@Overridepublic void run() {while (true) {try {Thread.sleep(5);} catch (InterruptedException e) {e.printStackTrace();}outputer.output("大師兄");}}}).start();}static class Outputer {Lock lock = new ReentrantLock();//字符串打印方法,一個個字符的打印public void output(String name) {int len = name.length();lock.lock();try {for (int i = 0; i < len; i++) {System.out.print(name.charAt(i));}System.out.println("");} finally {lock.unlock();}}}
}
?
總結
- 上一篇: 非互斥同步锁
- 下一篇: 是否允许一部分人“先富起来”