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

歡迎訪問 生活随笔!

生活随笔

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

编程问答

(三)线程同步工具集_2---控制并发访问资源的多个副本

發(fā)布時間:2024/4/14 编程问答 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 (三)线程同步工具集_2---控制并发访问资源的多个副本 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

2019獨角獸企業(yè)重金招聘Python工程師標準>>>

控制并發(fā)訪問資源的多個副本

在前面的記錄中使用binary semaphore實現(xiàn)了一個例子,這個例子是用來保護一個共享資源;但是semaphore也可以用來保護可以同時被多個線程訪問的多個共享資源副本或者臨界區(qū)副本;

在下面的例子中展示使用semaphore去保護多個資源的副本;

動手實現(xiàn)

1.創(chuàng)建一個PrintQueue

public class PrintQueue {// present printer that are free to print a jobprivate boolean freePrinters[];// Use this lock to protect the access to the freePrinters.private Lock lockPrinters;private final Semaphore semaphore;public PrintQueue() {this.semaphore = new Semaphore(3);freePrinters = new boolean[3];for (int i = 0; i < 3; i++) {freePrinters[i]=true;}lockPrinters=new ReentrantLock();}public void printJob(){try {semaphore.acquire();int assignedPrinter=getPrinter();long duration=(long)(Math.random()*10);System.out.printf("%s: PrintQueue: Printing a Job in Printer %d during %d seconds\n",Thread.currentThread().getName(),assignedPrinter,duration);TimeUnit.SECONDS.sleep(duration);freePrinters[assignedPrinter]=true;} catch (InterruptedException e) {e.printStackTrace();}finally {semaphore.release();}}private int getPrinter(){int ret=-1;lockPrinters.lock();try {for (int i = 0; i < freePrinters.length; i++) {if (freePrinters[i]) {ret=i;freePrinters[i]=false;break;}}} catch (Exception e) {e.printStackTrace();}finally {lockPrinters.unlock();}return ret;} }2.創(chuàng)建一個job

public class Job implements Runnable {private PrintQueue printQueue;public Job(PrintQueue printQueue) {this.printQueue = printQueue;}@Overridepublic void run() {System.out.printf("%s: Going to print a job\n",Thread.currentThread().getName());printQueue.printJob();System.out.printf("%s: The document has been printed\n",Thread.currentThread().getName());} }
3.Main

public class Main {public static void main(String[] args) {PrintQueue printQueue=new PrintQueue();Thread[] threads = new Thread[10];for (int i = 0; i < 10; i++) {threads[i] = new Thread(new Job(printQueue), "Thread_" + i);}for (int i = 0; i < 10; i++) {threads[i].start();}} }

要點

在上面的printJob方法中,semaphore每次可以是三個線程同時訪問,多余的線程將被阻塞;而進入的這三個線程又形成了競爭,而這里使用lock進一步去保護共享數(shù)據(jù),標記每一次可以訪問的線程,把索引記錄在freePrinters中;

轉(zhuǎn)載于:https://my.oschina.net/u/1387007/blog/343260

總結

以上是生活随笔為你收集整理的(三)线程同步工具集_2---控制并发访问资源的多个副本的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。