日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

代码演示:先来后到的特例、优劣、源码分析

發布時間:2024/4/13 编程问答 42 豆豆
生活随笔 收集整理的這篇文章主要介紹了 代码演示:先来后到的特例、优劣、源码分析 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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()方法,它是很猛的,它不遵守設定的公平的規則
例如,當有線程執行tryLock()的時候,一旦有線程釋放了鎖,那么這個正在tryLock()的線程就能獲取到鎖,即使在它之前已經有其他線程正在等待隊列里等待了

?

?

總結

以上是生活随笔為你收集整理的代码演示:先来后到的特例、优劣、源码分析的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。