我处于这样一种情况,我需要使用java.concurrent包中的Semaphore,以便我可以限制占用某个资源的线程数.以下是非常基本的设置(代码):
package semaphor;
import java.util.concurrent.Semaphore;
/**
* Created by NawazishMohammad on 15-04-2015.
*/
public class SemaphoreTester {
public static void main (String [] args){
new Thread(new MyRunnable(), "T1").start();
new Thread(new MyRunnable(), "T2").start();
new Thread(new MyRunnable(), "T3").start();
new Thread(new MyRunnable(), "T4").start();
}
}
class MyRunnable implements Runnable{
@Override
public void run() {
semaphoreStatus();
}
public void semaphoreStatus(){
System.out.println("Thread waiting for permit: "+Thread.currentThread().getName());
Semaphore sem = new Semaphore(2);
try {
sem.acquire();
System.out.println("Thread got permit: " + Thread.currentThread().getName());
System.out.println("Thread releasing permit: "+Thread.currentThread().getName());
sem.release(); …Run Code Online (Sandbox Code Playgroud) 由于某种原因,java.util.concurrent.ExecutorCompletionService它不使用java.util.concurrent.ExecutorService线程池中的线程.这会影响ExecutorCompletionService.submit()方法调用的"阻塞"执行.请考虑以下代码:
package completionservicedemo1;
import java.util.Date;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
public class CompletionServiceDemo1 {
static final ExecutorService executor = Executors.newFixedThreadPool(10, new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setName("Executor-Thread");
try {
System.out.println("Thread going to sleep: "+Thread.currentThread().getName());
thread.sleep(5000L);
System.out.println("Thread awakened: "+Thread.currentThread().getName());
} catch (InterruptedException ex) {
System.out.println("InteruptedException: "+ex);
}
return thread;
}
});
static final ExecutorCompletionService<String> completionService = new ExecutorCompletionService<>(executor);
static byte val=1;
public …Run Code Online (Sandbox Code Playgroud)