Java Multithreading Implementation callable interface _java

Source: Internet
Author: User
Tags static class stringbuffer

Invoke method:

/** * Click amount/month (year) callable/public void yearlyclickcallable () {//get parameter String year = Getpara ("Years");
 Statistical DataSet 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");
 Statistic data Set y list<integer> ylist = new arraylist<integer> (); Receive thread value list<future<list<map<string, object>>>> futurelist = new Arraylist<future<list
 <map<string, object>>>> ();
 Counter int count = 0;
 Create a thread pool (decide to open several threads) Executorservice pool = Executors.newcachedthreadpool ();
  Monthly log analysis for (int m = 1; M <= m++) {//Collect date parameter list<string> datelist = new arraylist<string> ();
  String date = ""; Judge how many days int day = Calendarutil.weekformonth (integer.valueof (yeaR), m);  Combination date for (int i = 1; I <= day; 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); }//Start future<list<map<string, object>>> Future = Pool.submit (New Readlogfilecallablebyyear (DateLis

  t));
 Futurelist.add (future);
 ///Close thread pool Pool.shutdown (); Receive result set for (future<list<map<string, object>>> future:futurelist) {try {//Receive parameters list<map& Lt

  String, object>> list = Future.get (1, timeunit.seconds);

   Sets the parameter for (int p = 0; p < list.size (); p++) {count + + (int) list.get (p). Get ("Clickcount");
   if (List.get (p). Get ("month"). Equals ("a")) {Ylist.add ((Integer) List.get (P). Get ("Clickcount")); else if (List.get (p). Get ("month"). Equals (")" {Ylist.add (Integer) List.get (P). Get ("Clickcount"));
   else if (List.get (p). Get ("month"). Equals ("")) {Ylist.add ((Integer) List.get (P). Get ("Clickcount"));
   else if (List.get (p). Get ("month"). Equals ("a") {Ylist.add ((Integer) List.get (P). Get ("Clickcount"));
   else if (List.get (p). Get ("month"). Equals ("a")) {Ylist.add ((Integer) List.get (P). Get ("Clickcount"));
   else if (List.get (p). Get ("month"). Equals ("the") {Ylist.add ((Integer) List.get (P). Get ("Clickcount"));
   else if (List.get (p). Get ("month"). Equals ("a") {Ylist.add ((Integer) List.get (P). Get ("Clickcount"));
   else if (List.get (p). Get ("month"). Equals ("the") {Ylist.add ((Integer) List.get (P). Get ("Clickcount"));
   else if (List.get (p). Get ("month"). Equals ("a")) {Ylist.add ((Integer) List.get (P). Get ("Clickcount"));
   else if (List.get (p). Get ("month"). Equals ("ten") {Ylist.add ((Integer) List.get (P). Get ("Clickcount")); else if (List.get (p). Get ("month"). Equals ("one")) {Ylist.add ((Integer) List.get (p). Get ("Clickcount"));
   else if (List.get (p). Get ("month"). Equals ("a") {Ylist.add ((Integer) List.get (P). Get ("Clickcount"));
  A catch (Exception e) {e.printstacktrace ());
 } setattr ("TotalCount", count);
 SetAttr ("x", xlist);
 SetAttr ("Y", ylist);
 Renderjson ();

 }

Multithreaded methods:

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; /** * Multithreading has return value * * @author darker * */public class Readlogfilecallablebyyear implements callable<list<map<
 String, object>>> {//date array private list<string> clickdate;

 Returns the result set 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 {//Receive parameters map<string, object>
 Map = new hashmap<string, object> (); Read file information using FileInputStream FileInputStream Fis = null;
 Using InputStreamReader for transcoding inputstreamreader reader = null;
 Using BufferedReader to buffer bufferedreader bufreader = null;
 Use StringBuffer to receive file content containers StringBuffer buf = new StringBuffer ();

 Click volume/month int monthclick = 0; for (int i = 0; i < clickdate.size (); i++) {//Get files file Clicklogfile = new (Constantutil.loglocation, "articl E.click. "
  + Clickdate.get (i) + ". txt"); To determine if a file exists if (!clicklogfile.exists () | | | clicklogfile.isdirectory ()) {System.err.println (Clickdate.get (i) +) does not exist
  
  ...");
  Map.put ("Month", Clickdate.get (i). substring (5, 7));
  Map.put ("Clickcount", 0);
  
  List.add (map);
  return list;
   else {try {//node stream FIS = new FileInputStream (clicklogfile);
   Conversion Stream reader = new InputStreamReader (FIS, "utf-8");
   Processing stream bufreader = new BufferedReader (reader);
   Counter int count = 0;
   Reads String line = "" by rows;
   Read file while (line = Bufreader.readline ())!= null) {//Count count++; Receive data 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 {//close stream try {bufreader.close ();
   Reader.close ();
   Fis.close ();
   catch (IOException e) {e.printstacktrace ();
 
 Result set 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;

 }

}

To share a user's example, but also very good

Import java.util.concurrent.Callable;
Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;

Import Java.util.concurrent.Future;
 The/** * callable and future interface * Callable are similar to runnable interfaces, and classes that implement callable interfaces and classes that implement runnable are tasks that can be performed by other threads.
 * There are several differences between callable and runnable: * (1) Callable The method specified is call (), and runnable the method specified is run (). 
 * (2) A callable task can return a value after execution, while a runnable task cannot return a value.
 * (3) The call () method throws an exception, and the run () method cannot throw an exception.
 * (4) Run callable task to get a future object, future represents the result of an asynchronous computation.
 * It provides a way to check whether the calculation is complete, to wait for the calculation to complete, and to retrieve the results of the calculation.
 * The Future object allows you to understand the execution of tasks, cancel the execution of the task, and get the results of the task execution. * * public class Callableandfuture {/** * Custom a task class, implement callable interface/public static class Mycallableclass implements C

		allable {//logo bit private int flag = 0;
		Public mycallableclass (int flag) {This.flag = flag;
			The public String called () throws Exception {if (This.flag = 0) {//If the flag value is 0, immediately returns return "flag = 0"; } if (This.flag = = 1) {//If flag value is 1, do an infinite loop try {while (true) {SYSTEM.OUT.PRIntln ("looping ...");
					Thread.Sleep (2000);
				The catch (Interruptedexception e) {System.out.println ("interrupted");
			Return "false";
			else {//Falg is not 0 or 1, throws an exception throw new Exception ("Bad flag value!"); }} public static void Main (string[] args) {//define tasks for 3 callable types Mycallableclass Task1 = new Mycallableclass (0
		);
		Mycallableclass task2 = new Mycallableclass (1);

		Mycallableclass task3 = new Mycallableclass (2);
		Create a service that performs a task Executorservice es = Executors.newfixedthreadpool (3);
			try {//Commit and execute the task, the task starts with a Future object,//If you want the result of a task execution or an exception to manipulate the Future object Future future1 = Es.submit (TASK1);

			Gets the result of the first task, and if the Get method is called, the current thread waits for the task to execute before executing System.out.println ("Task1:" + future1.get ());
			Future Future2 = Es.submit (TASK2); Wait 5 seconds before stopping the second task.
			Because the second task carried out is an infinite cyclic thread.sleep (5000);

			System.out.println ("Task2 Cancel:" + Future2.cancel (true)); Gets the output of the third task, because performing a third task causes an exception//So the following statement will cause an exception to be thrown Future future3 = ES.submit (TASK3);
		System.out.println ("TASK3:" + future3.get ());
		catch (Exception e) {System.out.println (e.tostring ());
	//Stop Task Execution Service Es.shutdownnow (); }
}

The above is the entire contents of this article, the need for small partners can refer to the following

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.