java并发信号量Semaphore

来源:互联网 发布:大数据营销经典案例 编辑:程序博客网 时间:2024/06/07 09:55
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();
}
}
}
}
原创粉丝点击