Java foundation-runnable and callable

Source: Internet
Author: User

The following test code, if the first future.get comment is canceled, that is, when the first submission of the task is completed, and then submit the same task, the re-submitted task will not be executed, because at this time the status of callable is not new. however, If the first future.get is commented out, that is, before the task submitted by the first submission is completed and the same task is submitted, the resubmitted task will still be executed because the status of callable is still NEW. This is different from using execute to submit runnable tasks, runnable itself is not identified by any state, note that callable itself has no state, but in the JDK The callable submitted in the executor framework will be packaged as Java.util.concurrent.FutureTask.

1 @Test2      public voidTestcallable ()throwsinterruptedexception, executionexception {3Executorservice executor = Executors.newfixedthreadpool (2);4 //int i = 0;5         FinalAtomicinteger i =NewAtomicinteger (0);6Callable<object> callable =NewCallable<object>() {7 @Override8              publicObject Call ()throwsException {9Thread.Sleep (1000);Ten System.out.println (i.incrementandget ()); one                 return NULL; a             } -         }; -future<object> future =Executor.submit (callable); the //Future.get (); - Executor.submit (callable); - Executor.shutdown (); - //Executor.shutdownnow (); +Executor.awaittermination (20000, timeunit.milliseconds); -}

Let's take a look at the main logic of executor commit (execute) runnable task

1         intc =Ctl.get ();2         //If the number of worker (thread of Execution) is less than corepoolsize, the worker is incremented and the command is the first work (Runnable)3         if(workercountof (c) <Corepoolsize) {4             if(addworker (command,true))5                 return;6c =Ctl.get ();7         }8         //Queue the command and check the executor status, if it is running but the number of workers is 0 (because Woker will be canceled when the idle time is reached, there may be a decrease of 0), (if the number of worker is less than maximumpoolsize) increase Woker9         if(isrunning (c) &&Workqueue.offer (COMMAND)) {Ten             intRecheck =Ctl.get (); one             if(! isrunning (recheck) &&Remove (COMMAND)) a Reject (command); -             Else if(workercountof (recheck) = = 0) -Addworker (NULL,false); the         } -         //finally, Try adding a worker, if not successfully stating that the executor was closed or the number of workers reached the maximum -         Else if(!addworker (command,false)) -Reject (command);

Come again executor submit (Submit) callable

1      public<T> future<t> Submit (callable<t>Task) {2         if(task = =NULL)Throw NewNullPointerException ();3         //Newtaskfor is to wrap the callable into a futuretask (runnablefuture implementation, the future represents the result of an asynchronous computation, Runnablefuture is the future inherits the runnable, represents the future of the executable, visible futuretask executable (real execution logic call is run wrapper), can obtain the calculation results (through wait, notify), It is also available for cancellation via Interrupt)4Runnablefuture<t> Ftask =newtaskfor (task);5         //Execute is the way to submit runnable6 Execute (ftask);7         returnftask;8}

Futuretask Class

1  public classFuturetask<v>ImplementsRunnablefuture<v> {2 3     ......4 5     Private volatile intstate ;6     Private Static Final intNEW = 0;7     Private Static Final intCompleting = 1;8     Private Static Final intNORMAL = 2;9     Private Static Final intexceptional = 3;Ten     Private Static Final intCANCELLED = 4; one     Private Static Final intinterrupting = 5; a     Private Static Final intInterrupted = 6; -  -     /**the underlying callable; nulled out after running*/ the     PrivateCallable<v>callable; -     /**the result to return or exception to throw from Get ()*/ -     PrivateObject outcome;//non-volatile, protected by State reads/writes -     /**the thread running the callable; Cased during run ()*/ +     Private volatileThread runner; -     /**Treiber Stack of waiting threads, there may be more than one thread get the same future,callable after the execution is complete, you need to notify all of these waiting threads*/ +     Private volatileWaitnode waiters; a  at     ...... -  -      publicFuturetask (callable<v>Callable) { -         if(callable = =NULL) -             Throw NewNullPointerException (); -          this. callable =callable; in          this. State = NEW;//ensure visibility of callable -     } to  +     ...... -}
View Code

In fact, we can call Futuretask ourselves completely.

1 @Test2      public voidTestfuturetask ()throwsexecutionexception, interruptedexception {3Futuretask<integer> Futuretask =NewFuturetask<> (NewCallable<integer>() {4 @Override5              publicInteger Call ()throwsException {6Thread.Sleep (1000);7                 return1;8             }9         });Ten         NewThread (futuretask). start (); oneInteger result =Futuretask.get (); aSystem.out.println (result);//1 -}
View Code

The shutdown of executor is interrupt all the work not executed,Shutdownnow is interrupt all work,awaittermination do not operate on the work, just to determine whether the executor has been terminated (shutdown, and no working in the execution, is terminated).

Java foundation-runnable and callable

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.