java.util.concurrentã便å©ããã
jdk1.5ã§å
¥ã£ããããjava.util.concurrentãé常ã«ä¾¿å©ã ã
Collectionç³»ããããã¨ãªãããExecutor&Callable&Futureã®3ã¤ã§å®ç¾ãããéåæå¦çãé常ã«ä¾¿å©ã ãä»ã¾ã§ã ã¨ã¹ã¬ããã¯Runnableãç¶æ¿ãã¦ããã®ã§åç´ãªå¤ã®è¿å´æ段ããªãã£ãããCallableã¯å¤ãè¿ããã¨ãåºæ¥ããã¾ãFutureãåç´ãªåæãã¨ã£ã¦ãããã
é常ã«åç´ãªä½¿ãæ¹ã¨ãã¦ã¯ãã¾ãjava.util.concurrent.Executorsã§é©å½ãªExecutorServiceãä½ãã次ã«éåæã«å¦çãããããã®ãsubmitã§ãã¥ã¼ã«è¿½å ãããããã¦Future.get()ã§çµæãåãåããFuture.get()ã¯ã¾ã å¦çä¸ãªãèªåçã«wait()ããã®ã§ç¹ã«ä»ã«åææ©æ§ã¯ãããªããã¾ããã¥ã¼ã«å
¥ããããå¦çãã©ããã£ãé ã§å¦çãããã®ãã¯ExecutorServiceã«ããã
é©å½ãªãµã³ãã«;
import java.util.concurrent.ExecutionException; import java.util.concurrent.Executors; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.Callable; public class Test{ public Test(int max){ ExecutorService e = Executors.newFixedThreadPool(3); Future<Integer>[] flist=new Future<Integer>[3]; flist[0]=e.submit(new Sumtask(0,max/3)); flist[1]=e.submit(new Sumtask(max/3+1,max*2/3)); flist[2]=e.submit(new Sumtask(max*2/3+1,max)); int ret=0; for(Future f:flist){ ret+=f.get().intValue(); } e.shutdown() } class SumTask implements Callable<Integer>{ int min,max; public SumTask(int min_,int max_){ min=min_; max=max_; } public Integer call(){ int ret=0; for(int i=min;i<=max;i++){ ret+=i; } return Integer.valueOf(i); } } public static void main(String[] args) { new Test(1000); } }