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();
}
}
}
}
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();
}
}
}
}