少年阿宾

那些青春的岁月

  BlogJava :: 首页 :: 联系 :: 聚合  :: 管理
  500 Posts :: 0 Stories :: 135 Comments :: 0 Trackbacks
//实例一,这里面用到了信号量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

posted on 2013-01-10 14:17 abin 阅读(663) 评论(0)  编辑  收藏 所属分类: JavaMultithread

只有注册用户登录后才能发表评论。


网站导航: