Java5 Concurrent Learning

Source: Internet
Author: User

source:http://lavasoft.blog.51cto.com/62575/115112 Java5 Concurrent Learning after Java5, the concurrency thread has changed radically, and the most important thing is a new stack of APIs to start, schedule, and manage threads. After Java5, it is better to start the thread by executor turndown with the thread start (). In the new feature, it is easy to control the threading startup, execution, and shutdown processes, and it is easy to use the thread pool features. first, create a taska task is a class that implements the Runnable interface. the real Run method is available when you create it. II. Implementation of the mandatethe task is performed through the Java.util.concurrent.ExecutorService interface object, which is created through a static method of the tool class java.util.concurrent.Executors. executors Factory and utility methods for the Executor, Executorservice, Scheduledexecutorservice, Threadfactory, and callable classes defined in this package. Executorservice provides methods for managing termination, as well as a way to generate a future for tracking one or more asynchronous task execution states. You can turn off Executorservice, which will cause it to stop accepting new tasks. When it is closed, the executing program terminates with no tasks executing, no tasks waiting to be executed, and new tasks cannot be submitted. Executorservice.execute (New testrunnable ());1. Create Executorservicecreated using the static method of the tool class java.util.concurrent.Executors. executors Factory and utility methods for the Executor, Executorservice, Scheduledexecutorservice, Threadfactory, and callable classes defined in this package. For example, to create an instance of Executorservice, Executorservice is actually a management tool for a thread pool:Executorservice executorservice = Executors.newcachedthreadpool ();Executorservice executorservice = Executors.newfixedthreadpool (3);Executorservice executorservice = Executors.newsinglethreadexecutor ();2. Add the task to the thread to executewhen adding a task to the thread pool, the thread pool will create one for each task, which will be executed automatically at a later point in time. Third, close the execution service objectExecutorservice.shutdown (); Iv. Comprehensive Examples
 Packageconcurrent;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;/*** Created by IntelliJ idea.**@authorleizhimin 2008-11-25 14:28:59*/ Public classTestcachedthreadpool { Public Static voidMain (string[] args) {//Executorservice executorservice = Executors.newcachedthreadpool ();Executorservice Executorservice = Executors.newfixedthreadpool (5);//Executorservice executorservice = Executors.newsinglethreadexecutor ();                 for(inti = 0; I < 5; i++) {Executorservice.execute (Newtestrunnable ()); System.out.println ("************* a" + i + "*************");        } executorservice.shutdown (); }}classTestrunnableImplementsRunnable { Public voidrun () {System.out.println (Thread.CurrentThread (). GetName ( )+ "The thread is called. ");  while(true) {                        Try{Thread.Sleep (5000);                        System.out.println (Thread.CurrentThread (). GetName ()); } Catch(interruptedexception e) {e.printstacktrace (); }                }        }}

Operation Result:

A0 ************************** A1 *************pool-1-thread-2 Thread was called. A2 *************pool-1-thread-3 thread was called. The pool-1-thread-1 thread was called. A3 ************************** A4 *************pool-1-thread-4 thread was called. The pool-1-thread-5 thread was called. pool-1-thread-2pool-1-thread-1pool-1-thread-3pool-1-thread-5pool-1-thread-4pool-1-thread-2pool-1-thread-1pool-1-thread-3p Ool-1-thread-5pool-1-thread-4 ...     
v. Get the return value of a task's executionafter Java5, the task is divided into two classes: one is the class that implements the Runnable interface, and the other is the class that implements the callable interface. Both can be executed by Executorservice, but the runnable task does not return a value, and the callable task has a return value. and callable's call () method can only be performed by the Executorservice's submit(callable<t> Task) method, and returns a <T> future<t A future that indicates that a task is waiting to be completed.
Callable<v>

A task that returns the result and may throw an exception. The implementing person defines a method called call without any parameters .

The callable interface is similar in Runnable that both are designed for classes whose instances might be executed by another thread. However, Runnable does not return a result and cannot throw a checked exception. Executors class contains some practical methods for converting from other ordinary forms to callable classes. the call () method in callable is similar to the runnable run () method, where the former has a return value and the latter does not. when a callable object is passed to the Executorservice's Submit method, the call method executes automatically on a thread and returns the execution result to the future object. Similarly, the Runnable object is passed to the Executorservice's Submit method, the Run method is executed automatically on a thread, and the execution result is returned to the future object, but the Get method is called on the future object. will return NULL. Unfortunately, in the Java API documentation, this piece of introduction is very confusing, it is estimated that the translator is not clear about it. Or a comment that is not in place. Let's look at an example:
Importjava.util.ArrayList;Importjava.util.List;Importjava.util.concurrent.*;/*** Callable Interface Test * *@authorleizhimin 2008-11-26 9:20:13*/ Public classCallabledemo { Public Static voidMain (string[] args) {Executorservice Executorservice=Executors.newcachedthreadpool (); List<Future<String>> resultlist =NewArraylist<future<string>>(); //Create 10 of tasks and execute                 for(inti = 0; I < 10; i++) {                        //use Executorservice to perform callable types of tasks and save the results in future variablesfuture<string> future = Executorservice.submit (NewTaskwithresult (i)); //to store task execution results in a listResultlist.add (future); }                //traverse the results of a task                 for(future<string>fs:resultlist) {                        Try{System.out.println (Fs.get ()); //Print the results of each thread (Task) execution}Catch(interruptedexception e) {e.printstacktrace (); } Catch(executionexception e) {e.printstacktrace (); } finally {                                //starts a sequential shutdown, performs a previously submitted task, but does not accept new tasks. If it is already closed, the call has no other effect. Executorservice.shutdown (); }                }        }}classTaskwithresultImplementsCallable<string> {        Private intID;  PublicTaskwithresult (intID) { This. ID =ID; }        /*** The specific process of the task, once the task is passed to Executorservice's Submit method, the method is automatically executed on a thread. *         * @return         * @throwsException*/         PublicString Call ()throwsException {System.out.println (The call () method is automatically called, Work!!! " +Thread.CurrentThread (). GetName ()); //a simulated time-consuming operation                 for(inti = 999999; i > 0; i--) ; returnThe call () method is called automatically, and the result of the task is: "+ ID +" "+Thread.CurrentThread (). GetName (); }}

Operation Result:

Call () method is automatically called, Work!!!             Pool-1-thread-1call () method is automatically called, Work!!!             Pool-1-thread-3call () method is automatically called, Work!!!             Pool-1-thread-4call () method is automatically called, Work!!!             Pool-1-thread-6call () method is automatically called, Work!!!             Pool-1-thread-2call () method is automatically called, Work!!!             The Pool-1-thread-5call () method is automatically called, the result of the task is: 0 Pool-1-thread-1call () method is automatically called, the result of the task is: 1 Pool-1-thread-2call () method is automatically called, Work!!!             Pool-1-thread-2call () method is automatically called, Work!!!             Pool-1-thread-6call () method is automatically called, Work!!!             The Pool-1-thread-4call () method is automatically called, the result of the task is: 2 Pool-1-thread-3call () method is automatically called, Work!!! The Pool-1-thread-3call () method is called automatically, and the result of the task is: the 3 Pool-1-thread-4call () method is called automatically, and the result of the task is: the 4 Pool-1-thread-5call () method is automatically called, The result of the task is: 5 The Pool-1-thread-6call () method is called automatically, the result of the task is: 6 Pool-1-thread-2call () method is called automatically, the result of the task is: 7 Pool-1-thread-6call () method is automatically called , the result of the task is: 8 The Pool-1-thread-4call () method is called automatically, the result of the task is: 9 pool-1-thread-3process finished with exit code 0

Java5 Concurrent Learning

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.