package concurrentTest;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;


public class SingletonMode {

 private static ConcurrentHashMap<String,FutureTask<T_T>> taskMap = new ConcurrentHashMap<String,FutureTask<T_T>>();
 private static CyclicBarrier barrier = new CyclicBarrier(50);
 private static boolean signal = true;
 private static final String KEY = "KEY";
 
 public static void main(String[] args) throws InterruptedException, ExecutionException {
  
  for(int i=0;i<100;i++){
   Thread thread = new Thread(new Runnable(){

    @Override
    public void run() {
     
     T_T t_t = null;
     try {
      t_t = O_O(KEY);
     } catch (InterruptedException e) {
      e.printStackTrace();
     } catch (ExecutionException e) {
      e.printStackTrace();
     }
     System.out.println(Thread.currentThread().getId() + "  " + t_t.getO_0());
    }
    
    public T_T O_O(String key) throws InterruptedException, ExecutionException{
     
     try {
      barrier.await();
     } catch (BrokenBarrierException e) {
      e.printStackTrace();
     }
     FutureTask<T_T> futureTask = taskMap.get(key);
     if(futureTask != null){
      System.out.println(Thread.currentThread().getId() + " 被阻塞到这里了.1");
     }else{
      futureTask = new FutureTask<T_T>(new Task(key));
      FutureTask<T_T> beforeTask = taskMap.putIfAbsent(key, futureTask);
      if(beforeTask == null){
       beforeTask = futureTask;
       beforeTask.run();
       signal = false;
      }else{
        futureTask = beforeTask;
      }
      if(signal)
       System.out.println(Thread.currentThread().getId() + " 被阻塞到这里了.2");
     }
     return futureTask.get();
    }
    
   });
   thread.start();
  }
 }
 
}

class Task implements Callable<T_T>{
 
 private String t;
 
 public Task(String t){
  this.t = t;
 }

 @Override
 public T_T call() throws Exception {
  return new T_T(t);
 }
}

class T_T{
 
 private String o_0;
 
 public String getO_0() {
  return o_0;
 }

 public void setO_0(String o_0) {
  this.o_0 = o_0;
 }

 public T_T(String o_0){
  
  try {
   Thread.currentThread().sleep(1000L);
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
  System.out.println(Thread.currentThread().getId() + " do it le");
  this.o_0 = o_0;
 }
}

 

posted on 2012-06-21 11:41  真心的不懂  阅读(404)  评论(0编辑  收藏  举报