代码演示:先来后到的特例、优劣、源码分析
生活随笔
收集整理的這篇文章主要介紹了
代码演示:先来后到的特例、优劣、源码分析
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
package lock.reentrantlock;import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;/*** 描述: 演示公平和不公平兩種情況*/
public class FairLock {public static void main(String[] args) {PrintQueue printQueue = new PrintQueue();Thread thread[] = new Thread[10];for (int i = 0; i < 10; i++) {thread[i] = new Thread(new Job(printQueue));}for (int i = 0; i < 10; i++) {thread[i].start();try {Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}}}
}class Job implements Runnable {PrintQueue printQueue;public Job(PrintQueue printQueue) {this.printQueue = printQueue;}@Overridepublic void run() {System.out.println(Thread.currentThread().getName() + "開始打印");printQueue.printJob(new Object());System.out.println(Thread.currentThread().getName() + "打印完畢");}
}class PrintQueue {private Lock queueLock = new ReentrantLock(true);public void printJob(Object document) {queueLock.lock();try {int duration = new Random().nextInt(10) + 1;System.out.println(Thread.currentThread().getName() + "正在打印,需要" + duration);Thread.sleep(duration * 1000);} catch (InterruptedException e) {e.printStackTrace();} finally {queueLock.unlock();}queueLock.lock();try {int duration = new Random().nextInt(10) + 1;System.out.println(Thread.currentThread().getName() + "正在打印,需要" + duration+"秒");Thread.sleep(duration * 1000);} catch (InterruptedException e) {e.printStackTrace();} finally {queueLock.unlock();}}
}
針對tryLock()方法,它是很猛的,它不遵守設定的公平的規(guī)則
例如,當有線程執(zhí)行tryLock()的時候,一旦有線程釋放了鎖,那么這個正在tryLock()的線程就能獲取到鎖,即使在它之前已經(jīng)有其他線程正在等待隊列里等待了
?
?
總結(jié)
以上是生活随笔為你收集整理的代码演示:先来后到的特例、优劣、源码分析的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 是否允许一部分人“先富起来”
- 下一篇: 共享锁和排它锁的用法