最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java多線程實(shí)現(xiàn)Callable接口

 更新時(shí)間:2016年06月19日 15:31:41   作者:Tsher2015  
本文給大家分享的是使用Java多線程來實(shí)現(xiàn)callable接口的方法,以及使用方法,另外還有一個(gè)網(wǎng)友的實(shí)例,希望能夠?qū)Υ蠹艺莆認(rèn)ava多線程有所幫助。

調(diào)用方法:

/**
 * 點(diǎn)擊量/月(年)Callable
 */
 public void yearlyClickCallable() {
 // 獲取參數(shù)
 String year = getPara("year");
 // 統(tǒng)計(jì)數(shù)據(jù)集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");
 // 統(tǒng)計(jì)數(shù)據(jù)集Y
 List<Integer> yList = new ArrayList<Integer>();
 // 接收線程值
 List<Future<List<Map<String, Object>>>> futureList = new ArrayList<Future<List<Map<String, Object>>>>();
 // 計(jì)數(shù)器
 int count = 0;
 // 創(chuàng)建一個(gè)線程池(決定開啟幾個(gè)線程)
 ExecutorService pool = Executors.newCachedThreadPool();
 // 每月的日志分析
 for (int m = 1; m <= 12; m++) {
  // 收集日期參數(shù)
  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);
  }
  // 啟動(dòng)
  Future<List<Map<String, Object>>> future = pool.submit(new ReadLogFileCallableByYear(dateList));

  futureList.add(future);
 }
 // 關(guān)閉線程池
 pool.shutdown();
 // 接收結(jié)果集
 for (Future<List<Map<String, Object>>> future : futureList) {
  try {
  // 接收參數(shù)
  List<Map<String, Object>> list = future.get(1, TimeUnit.SECONDS);

  // 設(shè)置參數(shù)
  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();
 }

多線程方法:

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>>> {
 // 日期數(shù)組
 private List<String> clickDate;
 // 返回結(jié)果集
 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 {
 // 接收參數(shù)
 Map<String, Object> map = new HashMap<String, Object>();
 // 利用FileInputStream讀取文件信息
 FileInputStream fis = null;
 // 利用InputStreamReader進(jìn)行轉(zhuǎn)碼
 InputStreamReader reader = null;
 // 利用BufferedReader進(jìn)行緩沖
 BufferedReader bufReader = null;
 // 利用StringBuffer接收文件內(nèi)容容器
 StringBuffer buf = new StringBuffer();
 // 點(diǎn)擊量/月
 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 {
   // 節(jié)點(diǎn)流
   fis = new FileInputStream(clickLogFile);
   // 轉(zhuǎn)換流
   reader = new InputStreamReader(fis, "utf-8");
   // 處理流
   bufReader = new BufferedReader(reader);
   // 計(jì)數(shù)器
   int count = 0;
   // 按行讀取
   String line = "";
   // 讀取文件
   while ((line = bufReader.readLine()) != null) {
   // 計(jì)數(shù)
   count++;
   // 接收數(shù)據(jù)
   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 {
   // 關(guān)閉流
   try {
   bufReader.close();
   reader.close();
   fis.close();
   } catch (IOException e) {
   e.printStackTrace();
   }
  }
  }
 }
 // 結(jié)果集
 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;
 }

}

再給大家分享一個(gè)網(wǎng)友的實(shí)例,也非常的不錯(cuò)

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * Callable 和 Future接口
 * Callable是類似于Runnable的接口,實(shí)現(xiàn)Callable接口的類和實(shí)現(xiàn)Runnable的類都是可被其它線程執(zhí)行的任務(wù)。
 * Callable和Runnable有幾點(diǎn)不同: 
 * (1)Callable規(guī)定的方法是call(),而Runnable規(guī)定的方法是run().
 * (2)Callable的任務(wù)執(zhí)行后可返回值,而Runnable的任務(wù)是不能返回值的。 
 * (3)call()方法可拋出異常,而run()方法是不能拋出異常的。
 * (4)運(yùn)行Callable任務(wù)可拿到一個(gè)Future對(duì)象, Future表示異步計(jì)算的結(jié)果。
 * 它提供了檢查計(jì)算是否完成的方法,以等待計(jì)算的完成,并檢索計(jì)算的結(jié)果。
 * 通過Future對(duì)象可了解任務(wù)執(zhí)行情況,可取消任務(wù)的執(zhí)行,還可獲取任務(wù)執(zhí)行的結(jié)果。
 */
public class CallableAndFuture {

	/**
	 * 自定義一個(gè)任務(wù)類,實(shí)現(xiàn)Callable接口
	 */
	public static class MyCallableClass implements Callable {
		// 標(biāo)志位
		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,做一個(gè)無限循環(huán)
				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個(gè)Callable類型的任務(wù)
		MyCallableClass task1 = new MyCallableClass(0);
		MyCallableClass task2 = new MyCallableClass(1);
		MyCallableClass task3 = new MyCallableClass(2);

		// 創(chuàng)建一個(gè)執(zhí)行任務(wù)的服務(wù)
		ExecutorService es = Executors.newFixedThreadPool(3);
		try {
			// 提交并執(zhí)行任務(wù),任務(wù)啟動(dòng)時(shí)返回了一個(gè)Future對(duì)象,
			// 如果想得到任務(wù)執(zhí)行的結(jié)果或者是異??蓪?duì)這個(gè)Future對(duì)象進(jìn)行操作
			Future future1 = es.submit(task1);
			// 獲得第一個(gè)任務(wù)的結(jié)果,如果調(diào)用get方法,當(dāng)前線程會(huì)等待任務(wù)執(zhí)行完畢后才往下執(zhí)行
			System.out.println("task1: " + future1.get());

			Future future2 = es.submit(task2);
			// 等待5秒后,再停止第二個(gè)任務(wù)。因?yàn)榈诙€(gè)任務(wù)進(jìn)行的是無限循環(huán)
			Thread.sleep(5000);
			System.out.println("task2 cancel: " + future2.cancel(true));

			// 獲取第三個(gè)任務(wù)的輸出,因?yàn)閳?zhí)行第三個(gè)任務(wù)會(huì)引起異常
			// 所以下面的語句將引起異常的拋出
			Future future3 = es.submit(task3);
			System.out.println("task3: " + future3.get());
		} catch (Exception e) {
			System.out.println(e.toString());
		}
		// 停止任務(wù)執(zhí)行服務(wù)
		es.shutdownNow();
	}
}

以上就是本文的全部?jī)?nèi)容了,有需要的小伙伴可以參考下

相關(guān)文章

最新評(píng)論

浠水县| 富顺县| 昭觉县| 鄂尔多斯市| 信丰县| 宁津县| 龙陵县| 额济纳旗| 雅江县| 丹东市| 扶余县| 张家界市| 会理县| 石首市| 油尖旺区| 澜沧| 铜山县| 平潭县| 汉中市| 黄龙县| 海晏县| 开江县| 洛阳市| 白沙| 永善县| 新干县| 中宁县| 万源市| 神木县| 浏阳市| 邵阳市| 呼和浩特市| 通榆县| 陇西县| 郸城县| 广南县| 库伦旗| 兴安县| 鄢陵县| 昭通市| 科技|