第一次使用線程池在網上搜索好長時間,感覺大概瞭解了皮毛,求指導

需要處理圖片,感覺變化不是太大 有時候很明顯 從 3000多 降到300多,而且未用線程池之前的方法執行 有時候也是幾十ms,有時候就差了十幾ms,也是醉了,不知道是不是使用錯誤

求指導。。。



public class TestCall<T> implements Callable<T>{

    /**
     * @param args
     */
    private int id;
    private  static ExecutorService pool = Executors.newCachedThreadPool();
    public TestCall(int i) {
        this.id = i ;
    }
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        List<Future<String[]>> results = new ArrayList<Future<String[]>>();
        for(int i=0;i<10;i++){
            results.add(pool.submit(new TestCall(i)));
        }
        for (Future<String[]> fs : results) {
            int k=0;
             while(!fs.isDone()){
                     System.out.println("等待.............."+k);
                     Thread.sleep(1);
                     k++;
                     if(k==10){
                         System.out.println("不等了.............."+k);
                         break;
                         }
                 }
             if (fs.isDone()) {
                    // 這裏的get方法,會將String的結果拿到。
                        System.out.println("結束"+fs.get());
                    }else{
                        System.out.println("任務未結束:");//+fs.get());
                    }
        }
        
          
        // TODO Auto-generated method stub
//        String[] widthAndh = {"這個","是","",""};
//        String[] widthAndHeigth = {"","","",""};
//        widthAndHeigth = widthAndh ;
//            widthAndHeigth[2]= Integer.toString(3);
//            widthAndHeigth[3]= "四級聯考";
//            String s = "null";
//            s.isEmpty();
//            System.out.println("是空?"+s.isEmpty());
//        for(int j=0;j<4;j++){
//            
//            System.out.println(widthAndHeigth[j]);
//        }
    }
    @Override
    public T call() throws Exception {
        if(Thread.currentThread().getName().contains("2")){
            System.out.print("繁瑣的任務。。。");
            for(int i=0;i<100;i++){
                
            }
            Thread.sleep(300000);
             System.out.println("任務是。。。"+Thread.currentThread().getName());
            }
//        Thread.sleep(200);
        return (T) ("result of TaskWithResult " + id+"當前線程:"+Thread.currentThread().getName());
    }

}


發佈了12 篇原創文章 · 獲贊 4 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章