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:
PublicStaticClass CyclicbarrierthreadExtendsthread{PrivateCyclicbarrier CB;PrivateIntSleepsecond;Public Cyclicbarrierthread (Cyclicbarrier CB,IntSleepsecond) {THIS.CB =cbThis.sleepsecond =Sleepsecond; }PublicvoidRun () {Try{System.out.println (This.getname () + "Run"); 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 ();} }}PublicStaticvoid main (string[] args) {Runnable Runnable = new Runnable () {public void run () {System.out.println ("All Threads of cyclicbarrier await () end, I run, time is" + System.currenttimemillis ()); } }; Cyclicbarrier cb = new cyclicbarrier (3new Cyclicbarrierthread (CB, 3 ); Cyclicbarrierthread cbt1 = new Cyclicbarrierthread (CB, 6 ); Cyclicbarrierthread cbt2 = new Cyclicbarrierthread (CB, 9 ); Cbt0.start (); Cbt1.start (); Cbt2.start ();}
Look at the results of the operation:
thread-0 ran thread-2 ran thread-1 ran thread-0 ready to wait, time for 1444650316313thread-1 ready to wait, Time for 1444650319313thread-2 ready to wait, all threads of Time 1444650322313CyclicBarrier await () end, I run, time is 1444650322313thread- 2 The end waited, the time for 1444650322313thread-0 ended waited, the time for the 1444650322313thread-1 end waited, the time for the 1444650322313
From the running results, as the same cyclicbarrier,thread-0 first ran to the await () place, wait, Thread-2 then run to await () place, still waiting, Thread-1 finally run to await () place, all Threads are running to 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 Rrunnable, 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
PublicStaticClass CallablethreadImplements Callable<string>{Public String Call ()ThrowsException {System.out.println ("Go to Callablethread Call () method, start sleeping, sleep time for" +System.currenttimemillis ()); Thread.Sleep (10000);return "123" ;}} public static void Main (string[] args) throws exception{executorservice es = Executors.newcachedthreadpool (); Callablethread ct = new Callablethread (); future<string> f = Es.submit (CT); Es.shutdown (); Thread.Sleep (5000 System.currenttimemillis ()); String str = F.get (); System.out.println ("Future has received data, str =" + str + ", Current time is" + System.currenttimemillis ());}
The result of the operation is:
Enter Callablethread call () method, start to sleep, sleep time for 1444654421368 main thread wait 5 seconds, the current time is 1444654426369Future has got data, str = 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:
PublicStaticClass CallablethreadImplements Callable<string>{Public String Call ()ThrowsException {System.out.println ("Go to Callablethread Call () method, start sleeping, sleep time for" +System.currenttimemillis ()); Thread.Sleep (10000);Return "123"; }}public static void Main (string[] args) throws exception{executorservice es = Executors.newcachedthreadpool (); Callablethread ct = new Callablethread (); futuretask<string> f = new futuretask<string> System.currenttimemillis ()); String str = F.get (); System.out.println ("Future has received data, str =" + str + ", Current time is" + System.currenttimemillis ());}
Look at the results of the operation:
Enter Callablethread call () method, start to sleep, sleep time for 1444655049199 main thread wait 5 seconds, the current time is 1444655054200Future has got data, str = 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