java學習筆記.04——執行緒池

qq_14926317發表於2015-10-31

執行緒池類:ExecutorServise


構造方法:

// 1
ExecutorService threadpool = Executors.newFixedThreadPool(n);  //建立n個執行緒的執行緒池

// 2
ExecutorService threadpool = ExecutorsnewCacheThreadPool();  // execute()多少次就建立多少執行緒  

具體操作:

ExecutorService threadpool = Executors.newFixedThreadPool(3);
for(int i = 0; i < 3; i++)
{
    threadpool.execute( new Runnable() {
        public void run()
        {
            ...
        }
    });
}


/*
 *Future Callable可以得到執行緒的返回值
 */
ExecutorService threadpool = Executors.newSingleThreadExecutor(); //注意構造方法
Future<String> future = threadpool.submit(new Callable<String>() {
    public String call() 
    {
        ...
    }
});

相關文章