java线程并发semaphore类示例

2022-10-20,,,,

复制代码 代码如下:
package com.yao;

import java.util.concurrent.executorservice;
import java.util.concurrent.executors;
import java.util.concurrent.semaphore;

/**
 * java 5.0里新加了4个协调线程间进程的同步装置,它们分别是:
 * semaphore, countdownlatch, cyclicbarrier和exchanger.
 * 本例主要介绍semaphore。
 * semaphore是用来管理一个资源池的工具,可以看成是个通行证,
 * 线程要想从资源池拿到资源必须先拿到通行证,
 * 如果线程暂时拿不到通行证,线程就会被阻断进入等待状态。
 */
public class mysemaphore extends thread {

 private int i;
 private semaphore semaphore;

 public mysemaphore(int i,semaphore semaphore){
  this.i = i;
  this.semaphore = semaphore;
 }

 public void run(){
  if(semaphore.availablepermits() > 0){
   system.out.println(""+i+"有空位 : ");
  }else{
   system.out.println(""+i+"等待,没有空位 ");
  }
  try {
   semaphore.acquire();
  } catch (interruptedexception e) {
   e.printstacktrace();
  }
  system.out.println(""+i+"获得空位");
  try {
   thread.sleep((int)math.random()*10000);
  } catch (interruptedexception e) {
   e.printstacktrace();
  }
  system.out.println(""+i+"使用完毕");
  semaphore.release();
 }
 public static void main(string[] args) {
  semaphore semaphore = new semaphore(2);
  executorservice service = executors.newcachedthreadpool();
  for(int i = 0 ;i<10 ; i++){
   service.execute(new mysemaphore(i,semaphore));
  }
  service.shutdown();
  semaphore.acquireuninterruptibly(2);
  system.out.println("使用完毕,需要清扫了");
  semaphore.release(2);
 }

}

《java线程并发semaphore类示例.doc》

下载本文的Word格式文档,以方便收藏与打印。