(三)线程同步工具集_2---控制并发访问资源的多个副本
生活随笔
收集整理的這篇文章主要介紹了
(三)线程同步工具集_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)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: A股博弈笔记
- 下一篇: 判断客户端是电脑还是手机