激情久久久_欧美视频区_成人av免费_不卡视频一二三区_欧美精品在欧美一区二区少妇_欧美一区二区三区的

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|

服務器之家 - 編程語言 - JAVA教程 - Java多線程實現Callable接口

Java多線程實現Callable接口

2020-05-18 12:29Tsher2015 JAVA教程

本文給大家分享的是使用Java多線程來實現callable接口的方法,以及使用方法,另外還有一個網友的實例,希望能夠對大家掌握Java多線程有所幫助。

調用方法:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
/**
 * 點擊量/月(年)Callable
 */
 public void yearlyClickCallable() {
 // 獲取參數
 String year = getPara("year");
 // 統計數據集X
 List<String> xList = new ArrayList<String>();
 xList.add("January");
 xList.add("February");
 xList.add("March");
 xList.add("April");
 xList.add("May");
 xList.add("June");
 xList.add("July");
 xList.add("August");
 xList.add("September");
 xList.add("October");
 xList.add("November");
 xList.add("December");
 // 統計數據集Y
 List<Integer> yList = new ArrayList<Integer>();
 // 接收線程值
 List<Future<List<Map<String, Object>>>> futureList = new ArrayList<Future<List<Map<String, Object>>>>();
 // 計數器
 int count = 0;
 // 創建一個線程池(決定開啟幾個線程)
 ExecutorService pool = Executors.newCachedThreadPool();
 // 每月的日志分析
 for (int m = 1; m <= 12; m++) {
  // 收集日期參數
  List<String> dateList = new ArrayList<String>();
  //
  String date = "";
  // 判斷有多少天
  int days = CalendarUtil.weekForMonth(Integer.valueOf(year), m);
  // 組合日期
  for (int i = 1; i <= days; i++) {
 
  if (i <= 9) {
 
   if (m <= 9) {
   date = year + "-0" + m + "-0" + i;
   } else {
   date = year + "-" + m + "-0" + i;
   }
  } else {
   if (m <= 9) {
   date = year + "-0" + m + "-" + i;
   } else {
   date = year + "-" + m + "-" + i;
   }
  }
  dateList.add(date);
  }
  // 啟動
  Future<List<Map<String, Object>>> future = pool.submit(new ReadLogFileCallableByYear(dateList));
 
  futureList.add(future);
 }
 // 關閉線程池
 pool.shutdown();
 // 接收結果集
 for (Future<List<Map<String, Object>>> future : futureList) {
  try {
  // 接收參數
  List<Map<String, Object>> list = future.get(1, TimeUnit.SECONDS);
 
  // 設置參數
  for (int p = 0; p < list.size(); p++) {
 
   count += (int) list.get(p).get("clickCount");
 
   if (list.get(p).get("month").equals("01")) {
   yList.add((Integer) list.get(p).get("clickCount"));
   } else if (list.get(p).get("month").equals("02")) {
   yList.add((Integer) list.get(p).get("clickCount"));
   } else if (list.get(p).get("month").equals("03")) {
   yList.add((Integer) list.get(p).get("clickCount"));
   } else if (list.get(p).get("month").equals("04")) {
   yList.add((Integer) list.get(p).get("clickCount"));
   } else if (list.get(p).get("month").equals("05")) {
   yList.add((Integer) list.get(p).get("clickCount"));
   } else if (list.get(p).get("month").equals("06")) {
   yList.add((Integer) list.get(p).get("clickCount"));
   } else if (list.get(p).get("month").equals("07")) {
   yList.add((Integer) list.get(p).get("clickCount"));
   } else if (list.get(p).get("month").equals("08")) {
   yList.add((Integer) list.get(p).get("clickCount"));
   } else if (list.get(p).get("month").equals("09")) {
   yList.add((Integer) list.get(p).get("clickCount"));
   } else if (list.get(p).get("month").equals("10")) {
   yList.add((Integer) list.get(p).get("clickCount"));
   } else if (list.get(p).get("month").equals("11")) {
   yList.add((Integer) list.get(p).get("clickCount"));
   } else if (list.get(p).get("month").equals("12")) {
   yList.add((Integer) list.get(p).get("clickCount"));
   }
 
  }
  } catch (Exception e) {
  e.printStackTrace();
  }
 }
 
 setAttr("totalCount", count);
 setAttr("x", xList);
 setAttr("y", yList);
 renderJson();
 }

多線程方法:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package com.ninemax.util.loganalysis;
 
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
 
import com.ninemax.util.loganalysis.tool.ConstantUtil;
 
/**
 * 多線程有返回值
 *
 * @author Darker
 *
 */
public class ReadLogFileCallableByYear implements Callable<List<Map<String, Object>>> {
 // 日期數組
 private List<String> clickDate;
 // 返回結果集
 public List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
 
 public ReadLogFileCallableByYear(List<String> clickDate) {
 this.clickDate = clickDate;
 }
 
 @Override
 public List<Map<String, Object>> call() throws Exception {
 // 接收參數
 Map<String, Object> map = new HashMap<String, Object>();
 // 利用FileInputStream讀取文件信息
 FileInputStream fis = null;
 // 利用InputStreamReader進行轉碼
 InputStreamReader reader = null;
 // 利用BufferedReader進行緩沖
 BufferedReader bufReader = null;
 // 利用StringBuffer接收文件內容容器
 StringBuffer buf = new StringBuffer();
 // 點擊量/月
 int monthClick = 0;
 
 for (int i = 0; i < clickDate.size(); i++) {
  // 獲取文件
  File clickLogFile = new File(ConstantUtil.LOGLOCATION, "article.click."+ clickDate.get(i) + ".txt");
  // 判斷文件是否存在
  if (!clickLogFile.exists() || clickLogFile.isDirectory()) {
 
  System.err.println(clickDate.get(i) + "的文件不存在...");
  
  map.put("month", clickDate.get(i).substring(5, 7));
  map.put("clickCount", 0);
  list.add(map);
  
  return list;
  } else {
  try {
   // 節點流
   fis = new FileInputStream(clickLogFile);
   // 轉換流
   reader = new InputStreamReader(fis, "utf-8");
   // 處理流
   bufReader = new BufferedReader(reader);
   // 計數器
   int count = 0;
   // 按行讀取
   String line = "";
   // 讀取文件
   while ((line = bufReader.readLine()) != null) {
   // 計數
   count++;
   // 接收數據
   if (!line.equals(null) && !line.equals("")) {
 
    buf.append(line + "\n");
   }
   }
   if (count == 0) {
   count = 0;
   } else {
   count = count - 1;
   }
   monthClick += count;
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   // 關閉流
   try {
   bufReader.close();
   reader.close();
   fis.close();
   } catch (IOException e) {
   e.printStackTrace();
   }
  }
  }
 }
 // 結果集
 map.put("month", clickDate.get(0).substring(5, 7));
 
 if (monthClick == 0) {
  map.put("clickCount", 0);
 } else {
  map.put("clickCount", monthClick);
 }
 
 list.add(map);
 
 return list;
 }
 
}

再給大家分享一個網友的實例,也非常的不錯

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
 
/**
 * Callable 和 Future接口
 * Callable是類似于Runnable的接口,實現Callable接口的類和實現Runnable的類都是可被其它線程執行的任務。
 * Callable和Runnable有幾點不同:
 * (1)Callable規定的方法是call(),而Runnable規定的方法是run().
 * (2)Callable的任務執行后可返回值,而Runnable的任務是不能返回值的。
 * (3)call()方法可拋出異常,而run()方法是不能拋出異常的。
 * (4)運行Callable任務可拿到一個Future對象, Future表示異步計算的結果。
 * 它提供了檢查計算是否完成的方法,以等待計算的完成,并檢索計算的結果。
 * 通過Future對象可了解任務執行情況,可取消任務的執行,還可獲取任務執行的結果。
 */
public class CallableAndFuture {
 
    /**
     * 自定義一個任務類,實現Callable接口
     */
    public static class MyCallableClass implements Callable {
        // 標志位
        private int flag = 0;
 
        public MyCallableClass(int flag) {
            this.flag = flag;
        }
 
        public String call() throws Exception {
            if (this.flag == 0) {
                // 如果flag的值為0,則立即返回
                return "flag = 0";
            }
            if (this.flag == 1) {
                // 如果flag的值為1,做一個無限循環
                try {
                    while (true) {
                        System.out.println("looping......");
                        Thread.sleep(2000);
                    }
                } catch (InterruptedException e) {
                    System.out.println("Interrupted");
                }
                return "false";
            } else {
                // falg不為0或者1,則拋出異常
                throw new Exception("Bad flag value!");
            }
        }
    }
 
    public static void main(String[] args) {
        // 定義3個Callable類型的任務
        MyCallableClass task1 = new MyCallableClass(0);
        MyCallableClass task2 = new MyCallableClass(1);
        MyCallableClass task3 = new MyCallableClass(2);
 
        // 創建一個執行任務的服務
        ExecutorService es = Executors.newFixedThreadPool(3);
        try {
            // 提交并執行任務,任務啟動時返回了一個Future對象,
            // 如果想得到任務執行的結果或者是異常可對這個Future對象進行操作
            Future future1 = es.submit(task1);
            // 獲得第一個任務的結果,如果調用get方法,當前線程會等待任務執行完畢后才往下執行
            System.out.println("task1: " + future1.get());
 
            Future future2 = es.submit(task2);
            // 等待5秒后,再停止第二個任務。因為第二個任務進行的是無限循環
            Thread.sleep(5000);
            System.out.println("task2 cancel: " + future2.cancel(true));
 
            // 獲取第三個任務的輸出,因為執行第三個任務會引起異常
            // 所以下面的語句將引起異常的拋出
            Future future3 = es.submit(task3);
            System.out.println("task3: " + future3.get());
        } catch (Exception e) {
            System.out.println(e.toString());
        }
        // 停止任務執行服務
        es.shutdownNow();
    }
}

以上就是本文的全部內容了,有需要的小伙伴可以參考下

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 黄色成人短视频 | 一区二区三区在线观看国产 | 97伦理| 高清视频一区二区 | 久久久久久精 | 中国成人在线视频 | 日日狠狠久久 | 久久精品亚洲一区 | 久久精品小短片 | 亚洲射吧| 国产jjizz一区二区三区视频 | 免费视频99 | 国产成年人视频 | 欧美精品一区二区久久 | 久久久www成人免费精品 | 欧美一级小视频 | 国产一级伦理片 | 色综合久久久久久久久久久 | 成人电影毛片 | 被啪羞羞视频在线观看 | 国产精品免费久久久久久 | 成人久久久久久久久久 | 国产精品1区2区在线观看 | 日韩黄色三级视频 | 国产乱xxxx | a网站在线 | 极品一级片 | 久草热久 | 在线免费观看精品 | 黄色免费小视频网站 | 91福利在线观看 | 日本一区二区三区视频在线 | 亚洲一区二区三区在线免费观看 | 亚洲网站在线观看 | 视屏一区 | 人成免费网站 | 日本中文字幕网址 | 亚洲精品欧美在线 | 国产午夜精品久久久 | 免费久久精品 | 成人久久久精品国产乱码一区二区 |