A further exploration of Java multithreading

Source: Internet
Author: User

We know that threads can be implemented by inheriting thread and implementing the Runnable interface, but they all have a disadvantage, that is, there is no return value after run, of course, we can solve the problem by passing in a variable in the thread, but it seems not always so reliable, okay, Java has given us additional interfaces callable and future.

Let's start by looking at their structure:

<span style= "FONT-SIZE:14PX;" >public interface callable<v>{        V call () throws Exception;    }        public interface future<v>{        V get () throws Exception;        V get (long timeout, timeunit unit) throws  Exception;        void Cancle (Boolean mayinterrput);        Boolean iscancelled ();        Boolean isDone ();    } </span>

in callable we can see that when call is called, it can return V, and what the future is, he can use to save the results of an asynchronous computation.

The first get and block are blocked until the calculation is complete and the result is returned, and the second one throws a timeoutexception exception if it times out.

If the calculation continues, IsDone () returns false, or True if it has already completed.

Cancle can cancel the calculation, if it has not started, it will not be run, if it has started, and Mayinterrupt is true, he will be interrupted.

There are also futuretask wrappers in Java that can convert callable into future and runnable. For example:

<span style= "FONT-SIZE:14PX;" >public static void Main (string[] args) throws Executionexception, interruptedexception {        Callable<integer > callable = new ...;        futuretask<integer> task = new futuretask<integer> (callable);        Thread thread = new thread (Task);        Thread.Start ();        Integer integer = Task.get ();    } </span>
Okay, it's time for me to feel really good.-----Actuator

If we create a lot of threads and then terminate their system, it will cost a lot of expense. So can we reuse them, yes, call the thread pool (thread pool).

The Actuator (Executor) class has many factory methods to build the thread pool. The following is a summary of the thread pool:

Newcachedthreadpool Create a new thread if necessary, the idle thread is retained for 60 seconds

Newfixedthreadpool The thread pool contains a fixed number of threads, and idle threads are kept

Newsinglethreadexecutor A "pool" of only one thread, which executes each submitted task in sequence

Newscheduledthreadpool fixed thread pool built for scheduled execution instead of Java.util.Timer

Newsinglescheduledexecutor single-threaded "pool" created for scheduled execution

Next we'll just say the top three.

They are all threadpoolexecutor classes that implement the Executorservice interface, and the following methods can be used to submit a task

<span style= "FONT-SIZE:14PX;" >        future<?> Submit (Runnable Task);        Future<t> Submit (Runnable task, T result);        Future<t> Submit (callable Task);</span>

The first, because the runnable itself does not return, but does not have enough information to formulate what the returned object is, so we can see that the return is FUTURE<?>, in fact, when invoking the future of get, but simply return null, of course, other methods can still be used.

The second is also a Runnable object, but with get, the top result object is returned.

Third, pass in a callable object and return the specified value.

Of course, after using a thread pool, remember to shutdown.

Let's look at an example:

<span style= "FONT-SIZE:14PX;" >class Counter implements callable<integer>{@Override public Integer call () throws Exception {Syst        Em.out.println (Thread.CurrentThread (). GetName () + "Counting");        int i;            for (i = 0; i <; i++) {if (i% = = 0) {System.out.println ();        } System.out.print (i + "");    } return i;        }}public class Forcallable {public static void main (string[] args) throws Interruptedexception, Executionexception {        Executorservice pool = Executors.newcachedthreadpool ();        Counter Counter = new Counter ();        future<integer> future = pool.submit (counter);        System.out.println (Thread.CurrentThread (). GetName () + ": I am Sleeping");        Thread.Sleep (5000);        System.out.println ("Get Value:" + future.get ());    Pool.shutdown (); }}</span>


Java multi-threaded re-explore

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.