Java Advanced-Multithreading (3)

Source: Internet
Author: User

1. The previous use of the threading API did not return the results, and Callable/future/futuretask was the solution to the problem, and in the process of calling

Make a capture of the exception

-callable executes the call () method to return an object or throw an exception;
callable is not like thread, but rather calls <T> future Executorservice.submit (callable<t> Task);
-future Returns a value that invokes the Get () method of the interface to return the corresponding object
------------------

Salescalculatesample.java> computes the result of each row and overlays the matrix through multithreading;

/** * * @author Lean @date: 2014-9-30 */public class Salescalculatesample {private static final int number_of_month=12;p rivate static final int number_of_customer=100;private static int[][] Cells;static class Summer implements Callable<in teger>{public int customerid;public Summer (int companyid) {This.customerid=companyid;} @Overridepublic Integer Call () throws Exception {int sum=0;for (int i = 0; i < Number_of_month; i++) {Sum+=cells[custom Erid][i];} System.out.printf ("customerid:%d, sum:%d\n", customerid,sum); return sum;}} public static void Main (string[] args) {Generatematrix (); Executorservice Executor=executors.newfixedthreadpool (10); Set<future<integer>> futures=new hashset<future<integer>> (); for (int i = 0; i < NUMBER_OF_ CUSTOMER; i++) {callable<integer> caller=new Summer (i); Futures.add (Executor.submit (caller));} Caculate the Sumint sum=0;for (future<integer> future:futures) {try {sum+=future.get ();} catch (Exception e) {E . printstackTrace ();} }system.out.println ("Sum is>>" +sum); Executor.shutdown ();} private static void Generatematrix () {cells=new int[number_of_customer][number_of_month];for (int i = 0; i < number_of_ CUSTOMER; i++) {for (int j = 0; J < Number_of_month; J + +) {cells[i][j]= (int) (Math.random () *100);}}}}

------------------


------------------

Cancancelprocessors> randomly cancels the submitted order (the futureprovides a canceled result execution )

/** * * @author Lean @date: 2014-10-7 */public class Cancancelprocessors {private static Executorservice Service=executo Rs.newfixedthreadpool (+);p rivate static final int orders_count=2000;private static Arraylist<future<integer >> futures=new arraylist<future<integer>> ();p ublic static void Main (string[] args) {for (int i = 0; I &l T;orders_count; i++) {Futures.add (Service.submit (New Orderexcutor (i))); New Thread (New Evilthread (Futures)). Start (); try {service.awaittermination (6,timeunit.seconds);} catch ( Interruptedexception e) {e.printstacktrace ();} int count=0;for (future<integer> future:futures) {if (future.iscancelled ()) {count++;}} System.out.println ("----------" +count+ "Orders canceled!---------"); Service.shutdown (); Static class Orderexcutor implements Callable<integer>{private int mid;public orderexcutor (int id) {this.mid=id;} @Overridepublic the Integer call () throws Exception {try {thread.sleep (+);} catch (Interruptedexception e) {}system.out.println ("Successfully execute OrderID:" +mid); return mId;}} Static class Evilthread implements Runnable{private arraylist<future<integer>> futures;public EvilThread ( Arraylist<future<integer>> futures) {this.futures=futures;} @Overridepublic void Run () {for (int i = 0; i < Orders_count; i++) {try {Thread.Sleep); Boolean flag=futures.get (i). Cancel (true); System.out.println ("Cancel order >" +flag + "by id>>" +i); catch (Interruptedexception e) {}}}}}
------------------



-futuretask integrates the functions of the runnable and the future interface, so it has the function of asynchronous and returning data;
------------------

Futuretasksample

/** * * @author Lean @date: 2014-9-30 */public class Futuretasksample {private static final int Number_of_month=12;priva Te static final int number_of_customer=100;private static int[][] Cells;static class Summer implements Callable<intege r>{public int customerid;public Summer (int companyid) {This.customerid=companyid;} @Overridepublic Integer Call () throws Exception {int sum=0;for (int i = 0; i < Number_of_month; i++) {Sum+=cells[custom Erid][i];} System.out.printf ("customerid:%d, sum:%d\n", customerid,sum); return sum;}} public static void Main (string[] args) {Generatematrix (); Set<futuretask<integer>> futures=new hashset<futuretask<integer>> (); for (int i = 0; i < Number_of_customer; i++) {callable<integer> caller=new Summer (i); futuretask<integer> futuretask=new futuretask<integer> (caller); Futuretask.run (); Futures.add ( Futuretask);} Caculate the Sumint sum=0;for (futuretask<integer> future:futures) {try {sum+=future.get ();} CATCH (Exception e) {e.printstacktrace ();}} System.out.println ("Sum is>>" +sum);} private static void Generatematrix () {cells=new int[number_of_customer][number_of_month];for (int i = 0; i < number_of_ CUSTOMER; i++) {for (int j = 0; J < Number_of_month; J + +) {cells[i][j]= (int) (Math.random () *100);}}}}

------------------
2.Executors
. Newfixedthreadpool () Create a fixed thread pool
. Newcachedthreadpool () Create a fixed thread pool, with each thread no longer created within 60 seconds
. Newsinglethreadexecutor () creates a single thread that is not destroyed
. Newscheduledexecutorservice () Create a thread that can be timed, delayed execution
------------------

Examples of scheduledcountsample> timing, time delay, numbers

/** *scheduledexecutorservicesample * * @author Lean @date: 2014-10-7 */public class Scheduledcountsample {private Stati C Scheduledexecutorservice Mservice=executors.newscheduledthreadpool (Ten);p rivate static final int avg=4;private  static final int mallcount=400;private static int mcurrencount=0;public static void main (string[] args) {//delay counting !//int times = mallcount/avg;//for (int i = 0; I < times; i++) {//mservice.schedule (new Trycount (i), I*1,timeunit.seco NDS);//}//mservice.scheduleatfixedrate (new Everycount (), 0, 1, timeunit.seconds); Mservice.schedulewithfixeddelay ( New Everycount (), 0, 1, timeunit.seconds);} Static class Everycount implements runnable{@Overridepublic void Run () {if (Mallcount>mcurrencount) { System.out.println ("threadid>>" +thread.currentthread (). GetId () + "and Count >>" +mcurrencount++);}}} Static class Trycount implements Callable<integer>{private int index;public trycount (int Index) {this. Index=index;} @Overridepublic Integer Call ()Throws Exception {for (int i = index*avg+0; I < (AVG+INDEX*AVG); i++) {System.out.println ("Count >>" +i);} SYSTEM.OUT.PRINTLN ("Thread Count end!"); return Index;}}}
------------------



-executorcompletionservice
usually get results with get (), the method forms a block.and take () to get the result of a task that has ended

------------------
Getresultrightnow

/** * Get non-blocking results * * @author Lean @date: 2014-10-7 */public class Getresultrightnow {public static void main (string[] args ) {int[] printnum={1000,200,200,30000,5000}; Arraylist<future<integer>> fetures=new arraylist<future<integer>> (); Executorservice executors = Executors.newfixedthreadpool (2); Executorcompletionservice<integer> service=new executorcompletionservice<integer> (executors); for (int I:printnum) {Fetures.add (Service.submit (New Getcurrnnum (i))); try {executors.awaittermination (5, Timeunit.seconds),} catch (Interruptedexception e) {e.printstacktrace ();} for (int i = 0; i < Printnum.length, i++) {int Num=0;try {//take It when there have a result;num = Service.take (). get (); Stop when there have no result no matter others having;//num=fetures.get (i). get (); catch (Interruptedexception e) {e.printstacktrace ();} catch (Executionexception e) {e.printstacktrace ();} SYSTEM.OUT.PRINTLN ("num is:" +num);} Executors.shutdown ();} Static Class Getcurrnnum IMplements callable<integer>{private int printnum;public getcurrnnum (int i) {printnum=i;} @Overridepublic Integer Call () throws Exception {try {thread.sleep (printnum);} catch (Exception e) {}return printnum;}}}
------------------



Java Advanced-Multithreading (3)

Related Article

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.