您的位置:首页 > 编程语言 > Java开发

java并发信号量Semaphore

2017-11-10 15:18 316 查看
package com.blocking;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

import java.util.concurrent.Semaphore;

public class ArrayCopy {

public static void main(String[] args) {

Semaphore semaphore=new Semaphore(2);
ExecutorService se = Executors.newCachedThreadPool();
ArrayCopy arrayCopy=new ArrayCopy();
se.submit(arrayCopy.new SemaphoreThread(semaphore, "a"));
se.submit(arrayCopy.new SemaphoreThread(semaphore, "b"));
se.submit(arrayCopy.new SemaphoreThread(semaphore, "c"));
se.submit(arrayCopy.new SemaphoreThread(semaphore, "d"));
se.submit(arrayCopy.new SemaphoreThread(semaphore, "e"));
se.submit(arrayCopy.new SemaphoreThread(semaphore, "f"));
se.submit(arrayCopy.new SemaphoreThread(semaphore, "g"));
se.submit(arrayCopy.new SemaphoreThread(semaphore, "h"));

se.shutdown();
}

// public static SemaphoreThread getInstance(Semaphore semaphore,String id){

// return new SemaphoreThread(semaphore, id);

// }

class SemaphoreThread implements Runnable{

Semaphore semaphore;

String id;

public SemaphoreThread(Semaphore semaphore,String id) {
this.semaphore=semaphore;
this.id=id;
}

@Override
public void run() {
try {
semaphore.acquire();
System.out.println("Thread:"+id+" acquire……");
Thread.sleep(2000);
semaphore.release();
System.out.println("Thread:"+id+" release……");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  并发