Java Multi-Threading 21: Cyclicbarrier, Callable, future, and futuretask for other components under multithreading

Source: Internet
Author: User

Cyclicbarrier

Then the other components under multithreading, the first thing to say is cyclicbarrier. Cyclicbarrier literally refers to the loop barrier, which can work with multiple threads, allowing multiple threads to wait in front of the barrier until all the threads have reached the barrier, and then continue to perform the subsequent actions together. Take a look at the usage examples of cyclicbarrier:

 Public Static classCyclicbarrierthreadextendsthread{PrivateCyclicbarrier CB; Private intSleepsecond;  PublicCyclicbarrierthread (Cyclicbarrier CB,intSleepsecond) {         This. cb =CB;  This. Sleepsecond =Sleepsecond; }             Public voidrun () {Try{System.out.println ( This. GetName () + "ran"); Thread.Sleep (Sleepsecond* 1000); System.out.println ( This. GetName () + "ready to wait, time for" +System.currenttimemillis ());            Cb.await (); System.out.println ( This. GetName () + "End of Wait, time" +System.currenttimemillis ()); }        Catch(Exception e) {e.printstacktrace (); }     }}     Public Static voidMain (string[] args) {Runnable Runnable=NewRunnable () { Public voidrun () {System.out.println ("Cyclicbarrier All threads await () ended, I ran, time was" +System.currenttimemillis ());    }    }; Cyclicbarrier CB=NewCyclicbarrier (3, runnable); Cyclicbarrierthread cbt0=NewCyclicbarrierthread (CB, 3); Cyclicbarrierthread cbt1=NewCyclicbarrierthread (CB, 6); Cyclicbarrierthread CBT2=NewCyclicbarrierthread (CB, 9);    Cbt0.start ();    Cbt1.start (); Cbt2.start ();}

Look at the results of the operation:

thread-0runs the thread-2runs the thread-1 runs the thread-0 is ready to wait, the time is 1444650316313Thread-  1 ready to wait, time is 1444650319313Thread-2 ready to wait, all threads of 1444650322313CyclicBarrier await () end, I run, Time is 1444650322313Thread-2 end waited, time is 1444650322313Thread-0 End waited, time is 1444650322313Thread- 1 ended up waiting, time was 1444650322313

From the results of the operation, as the same cyclicbarrier,thread-0 first run to await () place, wait, Thread-2 then run to await (), waiting, Thread-1 finally run to await () place, All threads run to the await (), so three threads and the specified runnable "simultaneously" run the following code, and you can see that after await (), four threads run exactly the same time, all 1444650322313.

From the use point of view, some people may think that Cyclicbarrier and countdownlatch a bit like, are many threads waiting for each other to complete, and then execute the following code. In fact, both Countdownlatch and cyclicbarrier are used for coordination between multiple threads, and several of the differences are:

1. Countdownlatch is triggered after multiple threads have Latch.countdown (), wake await () thread on Latch, execute countdown () thread, Finish countdown () will continue to work on its own thread;Cyclicbarrier is a fence that synchronizes all the threads that call the await () method, and when all the threads are in the await () method, the lines friend together to return to their respective work .

2, another countdownlatch and cyclicbarrier a difference is that countdownlatch can not be recycled, the counter minus 0 is reduced to 0, can not be reset, Cyclicbarrier can be recycled

3, Countdownlatch can evoke multiple threads of the task, Cyclicbarrier can only evoke a thread of the task

Note that because threads that use cyclicbarrier block on the await method, use Cyclicbarrier in the thread pool with great care, and if the thread pool has too few threads, a deadlock will occur

Callable, Future and Futuretask

Callable

Callable and Runnable, both of which are designed for classes whose instances might be executed by another thread, the main difference being that runnable does not return the result of the threading operation, callable can (if the thread needs to return the result of the run)

Future

A future is an interface that represents the result of an asynchronous calculation, which provides a way to check whether the calculation is complete, to wait for the calculation to complete, and to get the result of the calculation. The future provides a get (), Cancel (), Iscancel (), IsDone () Four methods, indicating that the future has three functions:

1, judge whether the task is completed

2. Interrupt Task

3. Get Task Execution Results

Futuretask

Futuretask is the implementation class for the future, which provides a basic implementation of the future. You can use Futuretask to wrap callable or runnable objects, because Futuretask implements Runnable, so you can also submit futuretask to executor.

How to use

Callable, future, and futuretask are generally used in conjunction with the thread pool, because the parent class of the thread pool Threadpoolexecutor Abstractexecutorservice provides three kinds of submit methods:

1. Public future<?> subit (Runnable Task) {...}

2. Public <T> future<t> submit<runnable task, T result>{...}

3. Public <T> future<t> submit<callable<t> task>{...}

The 2nd one is not used much, and the 1th and 3rd are more useful.

Callable+future Use Example

 Public Static classCallablethreadImplementsCallable<string>{     PublicString Call ()throwsException {System.out.println ("Call () method to enter Callablethread, start sleeping, sleep time for" +System.currenttimemillis ()); Thread.Sleep (10000); return"123"; }}     Public Static voidMain (string[] args)throwsexception{executorservice es=Executors.newcachedthreadpool (); Callablethread CT=NewCallablethread (); Future<String> f =Es.submit (CT);            Es.shutdown (); Thread.Sleep (5000); System.out.println ("The main thread waits 5 seconds, the current time is" +System.currenttimemillis ()); String Str=F.get (); System.out.println ("The future has got the data, str =" + str + ", the current time is" +System.currenttimemillis ());}

The result of the operation is:

= 123, current time is 1444654431369

See any one using the callable interface submit to the task, as long as there is a future to accept it, the future can be anywhere in the program to try to get the data returned from the thread, the time can be compared to a bit, just 10000ms, that is 10s

Callable+futuretask Use Example

Interested can look at the source code, in fact, using Callable+future Way, es.submit (CT) method returned to the future, the bottom realization of new comes out is a futuretask. So, let's look at the way Callable+futuretask:

 Public Static classCallablethreadImplementsCallable<string>{     PublicString Call ()throwsException {System.out.println ("Call () method to enter Callablethread, start sleeping, sleep time for" +System.currenttimemillis ()); Thread.Sleep (10000); return"123"; }}     Public Static voidMain (string[] args)throwsexception{executorservice es=Executors.newcachedthreadpool (); Callablethread CT=NewCallablethread (); Futuretask<String> f =NewFuturetask<string>(CT);    Es.submit (f);            Es.shutdown (); Thread.Sleep (5000); System.out.println ("The main thread waits 5 seconds, the current time is" +System.currenttimemillis ()); String Str=F.get (); System.out.println ("The future has got the data, str =" + str + ", the current time is" +System.currenttimemillis ());}

Look at the results of the operation:

= 123, current time is 1444655059200

As the result of the above, it does not explain

Benefits of using callable, future, and Futuretask

The above shows two examples, in fact, reflects a situation in reality, the above example to expand a little bit is:

There is a method () that executes method a returns a data for 10 seconds, the code after the A method is executed for 20 seconds, but the 20-second code has a 10-second method that does not depend on the execution result of method A, and a 10-second code relies on the execution result of method A. At this point, if the synchronous way, then it is bound to wait 10 seconds, wait for method A to complete, return data, and then execute the next 20 seconds of code.

It has to be said that this is a low-efficiency approach. With the callable, the future and the Futuretask, then:

1, first put the content of the A method into the call () method of the callable implementation class

2, Method () methods, callable implementation of the class passed into the executor of the Submit method

3. Execute code in the following method that does not depend on the result of method a for 10 seconds

4. Get the running result of method A, execute the code of 10 second dependent method A running result in the following method

This improves the efficiency of code execution, and the program does not have to be stuck in a method.

of course, you can also do without callable, in the way of implementing Runnable, the Run () method is done to think of a way to give a variable V in method () methods to assign a value. But as I said at the beginning of my last article, the reason to use multithreaded components is because the JDK helps us to get the code details right, so developers can focus on the logic of the business layer. If you use runnable, then we have to consider a lot of details ourselves, such as the Runnable implementation class of the run () method is executed to the V assignment is thread-safe, 10 seconds if the A method is not finished to cause V has no value to do, not to mention the JDK also provides the user to cancel the task, Determine whether a task exists, and so on. Since the JDK has helped us consider and implement these details, why should we write our own implementation of the run () method without compelling reasons?

Java Multi-Threading 21: Cyclicbarrier, Callable, future, and futuretask for other components under 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.