Multithreading-Callable interface implementation

Source: Internet
Author: User

The first two blogs (multithreading-inheriting the Thread class and multithreading-implementing the Runnable interface) introduced two methods for java to use the Thread. This blog continues to introduce the third method-implementing the Callable interface.

Let's talk about the differences between Runnable and Callable:

1. Callable specifies the call () method and Runnable specifies the run () method ().

2. Callable tasks can return values after execution, while Runnable tasks cannot return values.

3. The call method can throw an exception, but the run method cannot.

4. Run the Callable task to get a Future object, indicating the result of asynchronous calculation. It provides a method to check whether the computation is complete, waiting for the computation to complete and retrieving the computation results. You can use the Future object to understand the task execution status, cancel the task execution, and obtain the execution result.

The previous two blog examples are also used, but some changes are made here. Now we must not only enter the word length, but also calculate the sum of the length of all words in the string array.

Obviously, with such a change, the multi-thread execution body needs a return value to calculate the sum of the length of all words. The run method in runnable cannot return values. Therefore, we can only use callable here. The Code is as follows:

Package test; import java. util. hashSet; import java. util. set; import java. util. concurrent. callable; import java. util. concurrent. executionException; import java. util. concurrent. executorService; import java. util. concurrent. executors; import java. util. concurrent. future; public class Test1 {public static void main (String [] args) {String [] words = {"first", "second", "world", "thread "}; // create a thread pool ExecutorService pool = Executors. newCachedThreadPool (); Set
 
  
> Set = new HashSet
  
   
> (); For (String word: words) {Callable
   
    
Callable = new testCallable (word); Future
    
     
Future = pool. submit (callable); set. add (future);} int sum = 0; for (Future
     
      
Future: set) {try {sum + = future. get ();} catch (InterruptedException e) {e. printStackTrace ();} catch (ExecutionException e) {e. printStackTrace () ;}} System. out. println ("the total length of all words in the array is:" + sum) ;}} class testCallable implements Callable
      
        {Private String word; public testCallable (String word) {this. word = word;} @ Overridepublic Integer call () throws Exception {System. out. println (Thread. currentThread (). getName () + ": start execution! "); Try {// assume that it takes 2 seconds to process the Thread. currentThread (). sleep (2000);} catch (InterruptedException e) {e. printStackTrace ();} System. out. println (Thread. currentThread (). getName () + ": processing! "); System. out. println (Thread. currentThread (). getName () + ":" + word + "Length:" + word. length (); return Integer. valueOf (word. length ());}}
      
     
    
   
  
 

The execution result is as follows:

Pool-1-thread-1: start execution!
Pool-1-thread-3: start execution!
Pool-1-thread-4: start execution!
Pool-1-thread-2: start execution!
Pool-1-thread-1: processing!
Pool-1-thread-1: first length: 5
Pool-1-thread-3: processing!
Pool-1-thread-3: world length: 5
Pool-1-thread-2: processing!
Pool-1-thread-2: second length: 6
Pool-1-thread-4: processing!
Pool-1-thread-4: thread length: 6
The total length of all words in the array is: 22

Now, all three methods for creating threads in java are described. Of course, after learning about these things, we can only explain that you have just started with multithreading,

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.