통화 방법 :
/** * 클릭 수/월 (연도) 호출 가능 */public void yearclickCallable () {// 매개 변수 얻기 문자열 연도 = getPara ( "Year"); // 통계 데이터 세트 x 목록 <string> xlist = new Arraylist <string> (); xlist.add ( "1 월"); xlist.add ( "2 월"); xlist.add ( "March"); xlist.add ( "4 월"); xlist.add ( "May"); xlist.add ( "6 월"); xlist.add ( "7 월"); xlist.add ( "7 월"); xlist.add ( "8 월"); xlist.add ( "9 월"); xlist.add ( "10 월"); xlist.add ( "11 월"); xlist.add ( "12 월"); // 통계 데이터 세트 y 목록 <integer> ylist = new ArrayList <integer> (); // 스레드 값 목록 수신 <future <list <map <string, object >>>>>> futurelist = new arraylist <future <list <map <string, object >>> (); // counter int count = 0; // 스레드 풀 생성 (시작할 스레드 수 결정) ExecutorService Pool = Executor.NewCachedThreadPool (); // (int m = 1; m <= 12; m ++)에 대한 월간 로그 분석 {// 날짜 매개 변수 수집 목록 <string> datelist = new ArrayList <string> (); // 문자열 날짜 = ""; // int days = calendarutil.weekformonth (integer.valueof (년), m); // (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 (날짜); } // start future <list <map <string, object >>> future = pool.submit (new readLogFileCallableByyear (datelist)); futurelist.add (미래); } // 스레드 풀 풀을 닫습니다 .Shutdown (); // 결과 세트를 수신합니다 (Future <list <map <string, object >>>> future) {try {// 매개 변수 목록을 수신 <map <string, object >>> list = future.get (1, timeUnit.seconds); // (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 ((정수) list.get (p) .get ( "clickcount")); } else if (list.get (p) .get ( "month"). equals ( "03")) {ylist.add ((정수) list.get (p) .get ( "clickcount")); } else if (list.get (p) .get ( "month"). equals ( "03")) {ylist.add ((정수) list.get (p) .get ( "clickcount")); } else if (list.get (p) .get ( "month"). equals ( "03")) {ylist.add ((정수) 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 ( "06")) {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 ( "09")) {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 (예외 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; hashmap; java.util.map; import java.util.concurrent.callable; import com.ninemax.util.loganalysis.tool.constantutil;/** * multithreaded return value * * @author darker */public class readlogfilecallablebyyyear emplements <string >> // // // 반환 결과 세트 공개 목록 <map <string, object >>> list = new ArrayList <map <String, Object >> (); public readLogFileCallableByyEar (list <string> clickDate) {this.ClickDate = clickDate; } @override public list <map <string, object >> call () rows exception {// 매개 변수를 받으십시오. <문자열, 개체> map = new Hashmap <string, object> (); // fileInputStream을 사용하여 파일 정보를 읽습니다. fileInputStream fis = null; // inputStreamReader를 사용하여 transcode inputStreamReader reader = null; // bufferedReader를 사용하여 버퍼 버퍼드 리더 bufreader = null; // StringBuffer를 사용하여 파일 컨텐츠 컨텐츠를받습니다. StringBuffer buf = new StringBuffer (); // 클릭/월 int monthclick = 0; for (int i = 0; i <clickdate.size (); i ++) {// 파일 파일 가져옵니다. clickLogFile = 새 파일 (constantUtil.loglocation, "article.click."+ clickDate.get (i)+ ".txt"); // 파일이 존재하는지 여부를 결정합니다 (! 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 (지도); 반환 목록; } else {try {// node stream fis = new FileInputStream (clickLogFile); // stream reader 변환 = new inputStreamReader (FIS, "UTF-8"); // 스트림 처리 bufreader = new bufferedReader (Reader); // counter int count = 0; // 문자열 line = ""; // 파일 읽기 while ((line = bufreader.readline ())! = null) {// count count ++; // if (! line.equals (null) &&! line.equals ( "")) {buf.append (line + "/n"); }} if (count == 0) {count = 0; } else {count = count -1; } MonthClick += count; } catch (예외 e) {e.printstacktrace (); } 마침내 {// 닫기 스트림 try {bufreader.close (); reader.close (); fis.close (); } catch (ioexception e) {e.printstacktrace (); }}}} // result set set map.put ( "month", clickdate.get (0) .substring (5, 7)); if (monthclick == 0) {map.put ( "ClickCount", 0); } else {map.put ( "ClickCount", MonthClick); } list.add (지도); 반환 목록; }}네티즌의 예를 여러분과 공유하겠습니다.
import java.util.concurrent.callable; import java.util.concurrent.executorservice; import java.util.concurrent.concurrent; import java.util.concurrent.future;/*** 호출 가능하면 런닝 가능과 유사합니다. Callable 인터페이스를 구현하는 클래스 및 런 가능성을 구현하는 클래스는 다른 스레드에서 실행할 수있는 작업입니다. * Callable 및 Runnable에는 몇 가지 차이점이 있습니다. * (1) Callable에 의해 지정된 메소드는 Call ()이며 Runnable에 의해 지정된 메소드는 run ()입니다. * (2) 호출 가능한 작업은 실행 된 후 값을 반환 할 수 있지만, 실행 가능한 작업은 값을 반환 할 수 없습니다. * (3) Call () 메소드는 예외를 던질 수 있지만 run () 메소드는 예외를 던질 수 없습니다. * (4) 호출 가능한 작업을 실행하면 미래의 개체를 얻을 수 있습니다. 미래는 비동기 계산의 결과를 나타냅니다. * 계산이 완료되었는지 확인하고 계산이 완료 될 때까지 대기하고 계산 결과를 검색하는 방법을 제공합니다. * 미래의 객체를 통해 작업 실행 상태를 이해하고 작업 실행을 취소하고 작업 실행 결과를 얻을 수 있습니다. */public class CallableAndFuture {/***호출 가능한 인터페이스를 구현하기 위해 작업 클래스를 사용자 정의하십시오*/public static class mycallableClass는 호출 가능 {// flag bit private int flag = 0; public myCallableClass (int flag) {this.flag = flag;} public string call () {this.flag = 0) {// if 0) {// iS 0). 0 ";} if (this.flag == 1) {// 플래그의 값이 1이면 무한 루프를 시도하십시오 {while (true) {system.out.println ("루핑 ... "); thread.sleep (2000);}} catch (InteruptedException e) {system.out.println ("}}}} retong "); 0 또는 1, 그런 다음 예외가 발생합니다. 새로운 예외 ( "나쁜 깃발 값!");}}} public static void main (String [] args) {// 3 호출 가능한 유형 task1 = new mycallableClass (0); mycallableClass task2 = new mycallableClass (1); mycallablass task3 = 새로운 mycallbesblass (2); ExecutorService es = executors.newfixedThreadpool (3); try {// 작업을 제출하고 실행하십시오. 작업이 시작되면 미래의 객체가 반환됩니다. // 작업 실행 결과 또는 예외를 얻으려면 미래의 객체를 작동 할 수 있습니다. Future Future1 = es.submit (task1); // 첫 번째 작업의 결과를 얻습니다. get 메소드가 호출되면 현재 스레드는 System.out.println ( "task1 :" + future1.get ()); Future Future2 = es.submit (task2); // 두 번째 작업을 중지하기 전에 5 초 동안 기다립니다. 두 번째 작업은 무한 루프 스레드 (5000); System.out.println ( "task2 cancel :" + future22.cancel (true))이기 때문에 세 번째 작업을 실행하면 예외가 발생할 수 있으므로 다음 문장은 미래의 미래 = es.submit (task3); " + 미래의 (task3)); (예외 e) {system.out.println (e.toString ());} // 작업 실행 서비스 중지 es.shutdownNow ();}}위는이 기사의 전체 내용입니다. 필요한 경우 참조하십시오.