Java多线程~~~使用信号量来控制资源获取
来源:互联网 发布:汽车修理厂软件 编辑:程序博客网 时间:2024/05/21 17:01
在多线程开发中,有一个很经典的名词,那就是信号量。信号量就是用来衡量一个资源的可利用数目的,根据信号
量的多少来控制在多线程中各个资源之间的冲突问题,在Java中也提供了对信号量的支持。
而且在创建信号量的时候,第二个参数用来指定采取何种分配策略,比如当有很多线程被阻塞,但有一个机会的时
候,信号量应该选择谁去运行呢,如果选择true,就采用公平模式,到时候看哪个线程等待的时间最久,就把机会给那
个等待最久的线程,这样的就是公平分配策略。
下面就用代码来说明一下问题
package com.bird.concursey.charpet4;import java.util.concurrent.Semaphore;public class PrintQueue {// It initializes the semaphore object that will protect the access from the// print queue.private final Semaphore semaphore = new Semaphore(1,true);public void printJob(Object document) {//you must acquire the semaphore callingtry {semaphore.acquire();long duration = (long)(Math.random()*10);System.out.printf("%s: PrintQueue: Printing a Job during %d seconds\n",Thread.currentThread().getName(),duration);Thread.sleep(duration);} catch (InterruptedException e) {e.printStackTrace();}finally{//free the semaphore by calling the release() method of the semaphore.semaphore.release();}}}
package com.bird.concursey.charpet4;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(new Object());System.out.printf("%s: The document has been printed\n",Thread.currentThread().getName());}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), "Thread " + i);}for(int i = 0; i < 10; i++) {thread[i].start();}}}
0 0
- Java多线程~~~使用信号量来控制资源获取
- java多线程控制-信号量Semaphore
- C# 使用Semaphore(信号量)控制多线程
- C# 使用Semaphore(信号量)控制多线程
- java多线程Thread-Semaphore控制信号量
- 多线程 : Java 信号量 Semaphore 使用
- java多线程-Semaphore信号量使用
- java多线程-Semaphore信号量使用
- 多线程信号量控制
- 使用相对路径来获取资源
- 使用代理服务器来获取网上的资源
- java TheadLocal 多线程资源使用
- 使用信号量管理多线程
- 多线程之使用信号量
- 多线程信号量的使用
- 多线程信号量的使用
- Java多线程 -- 信号量
- JAVA多线程--信号量(Semaphore)
- OpenCV基础篇之图片叠加
- 木兰词
- 零基础汇编揭开CPU的神秘面纱(堆栈、CPU保护模式)
- 循环的角度求均值
- Android API
- Java多线程~~~使用信号量来控制资源获取
- linux 代码性能分析工具 介绍
- OpenCV基础篇之使用CMake管理工程
- OC 基础学习4--NSDictionary
- javaweb做一个计算器
- OpenCV基础篇之查找表
- Android eclipse中程序调试
- Web缓存的作用与类型
- 【LeetCode】-Insertion Sort List