//实例一,这里面用到了信号量Semaphore和FutureTask
package net.abin.lee.mythread.callable;
import java.util.concurrent.Callable;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class FutureGo implements Callable<String> {
private String message;
private static final Semaphore semaphore=new Semaphore(3);
private final ReentrantReadWriteLock rwl=new ReentrantReadWriteLock();
public FutureGo(String message) {
this.message = message;
}
public String call() throws InterruptedException {
semaphore.acquire();
Lock read=rwl.readLock();
Lock write=rwl.readLock();
read.lock();
System.out.println("message"+message+",Name"+Thread.currentThread().getName()+"进来了");
read.unlock();
write.lock();
String result=message+"你好!";
Thread.sleep(1000);
System.out.println("message"+message+"Name"+Thread.currentThread().getName()+"离开了");
write.unlock();
semaphore.release();
return result;
}
}
//FutureTaskTest.java
package net.abin.lee.mythread.callable;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
public class FutureTaskTest {
public static void main(String[] args) throws InterruptedException,
ExecutionException {
Callable<String> go = new FutureGo("abin");
FutureTask<String> task = new FutureTask<String>(go);
ExecutorService executor = Executors.newCachedThreadPool();
if (!executor.isShutdown()) {
executor.execute(task);
}
String result = "";
if (!task.isDone()) {
result = (String) task.get();
System.out.println("result=" + result);
}
executor.shutdown();
}
}
//实例一,这里面用到了信号量Semaphore和FutureTask