Java implementation of multi-threaded collation:
- Thread implements multithreading in two ways:
(1) inherit the thread class while overloading the Run method:
class extends Thread { long minprime; Primethread (long minprime) { this. minprime = minprime; } Public void run () { // compute primes larger than minprime }}
Primethread p = new Primethread (143);
P.start ();
Thread's source code:
Public class Implements Runnable { /**/ privatestaticnative void registernatives (); Static { registernatives (); } ......
/* What'll be run. */
Private Runnable target;
/**
* If This thread is constructed using a separate
* <code>runnable</code> Run object, Then
* <code>runnable</code> object ' s <code>run</code> method is called;
* Otherwise, this method does nothing and returns.
* <p>
* Subclasses of <code>thread</code> should override this method.
*
* @see #start ()
* @see #stop ()
* @see #Thread (Threadgroup, Runnable, String)
*/
@Override
public Void Run () {
if (target! = null) {
Target.run ();
}
}
}
(2) Declare a class that implements the Runnable interface. ---The Thread class is actually the class that implements the Runnable interface, see the source code above
Package Java.lang; Public Interface Runnable { publicabstractvoid run ();}
If you do not need to implement the other methods in the thread class, you can implement multithreading only by implementing the Run () method in the Runnable interface.
Important because classes should not being subclassed unless the programmer intends on modifying or enhancing the FU Ndamental behavior of the class. "---Arthur van Hoff
---because when programmers are not ready to modify or enhance the functionality of this class, they should not be a subclass of this class.
class Implements Runnable { long minprime; Primerun (long minprime) { this. minprime = minprime; } Public void run () { //compute primes larger than minprime ... } }
Primerun p = new Primerun (143); new Thread (P). Start ();
2. Executors
Executor interface
An object that executes the commit runnable task. The implementation of the task and the execution of the task, the use of the thread, scheduling decoupling.
Replace the new Thread (New (Runnabletask ())). Start ()
Instead use:
Executor Executor = Anexecutor;
Executor.execute (New RunnableTask1 ());
Executor.execute (New RunnableTask2 ());
Simple to use:
class Implements Executor { publicvoid execute (Runnable r) { r.run (); class Implements Executor { publicvoid execute (Runnable r) { new Thread (R). Start (); } }
A composite executor:
classSerialexecutorImplementsExecutor {Finalqueue<runnable> tasks =NewArraydeque<runnable>(); FinalExecutor Executor; Runnable active; Serialexecutor (Executor Executor) { This. Executor =executor; } Public synchronized voidExecuteFinalRunnable R) {Tasks.offer (NewRunnable () { Public voidrun () {Try{r.run (); } finally{schedulenext (); } } }); if(Active = =NULL) {schedulenext (); } } protected synchronized voidSchedulenext () {if((active = Tasks.poll ())! =NULL) {Executor.execute (active); } } }
Interface Executorservice
Interface inheritance Executor provides methods to manage termination and synchronous or asynchronous tasks that can produce future results.
Public InterfaceExecutorserviceextendsExecutor {
void shutdown ();//stop talking about tasks and no longer receive new tasks
List<runnable> Shutdownnow ();//Stop all active tasks, stop waiting for the task, and return the list of waiting tasks to be performed.
Boolean IsShutDown (); Returns true if executor has been stopped
Boolean isterminated (); Returns true if all tasks have been completed after shutdown. Only shutdown () or Shutdownnow () is called to return true.
Boolean awaittermination (long timeout, timeunit) throws interruptedexception; Blocks until all tasks are completed in the shutdown () request, or the timeout occurs, or the existing thread is interrupted.
<T> future<t> Submit (callable<t> Task); Submits a value returned by the task to run, while returning the future class, through the future of the Get () method to obtain the execution results of the task.
<T> future<t> Submit (Runnable task, T result);
Future<?> Submit (Runnable Task);//Submit a Runnable task to execute and return a future to represent this task.
<T> list<future<t>> InvokeAll (colleaciton<? extends callable<t>> tasks) throws interruptedexception;//executes the specified number of tasks, returns a list of the future, contains their status, and runs the completed results.
<T> list<future<t>> InvokeAll (collectio<? extends callable<t>> tasks, long timeout, Timeunit unit) throws interruptedexception;//performs the given task, returns the list of future, knowing that all tasks are complete or time-out is reached.
<T> T invokeany (collection<? extends callable<t>> tasks) throws Interruptedexception, executionexception;//executes the given task and returns the result of any one completed.
<T> T invokeany (collection<? extends callable<t>> tasks, long timeout, timeunit unit) throws Interrupte Dexception, Executionexception, timeoutexception;//perform the given task until the task completes within the time-out period
}
Class executors
Supports running asynchronous tasks and managing a thread pool without having to manually create new threads.
Public class Executors { publicstaticvoid main (string[] args) { = Executors.newsinglethreadexecutor (); {= thread.currentthread (). GetName (); System.out.println ("Hello" + threadname);} );} }
But the Java process does not end, executors must show the stop, can call the method in the above Executorservice to terminate: Shutdown () will wait for the current task to complete, Shutdownnow () All currently running tasks are terminated and executor is immediately closed.
ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;ImportJava.util.concurrent.TimeUnit; Public classExecutors { Public Static voidMain (string[] args) {Executorservice executor=Executors.newsinglethreadexecutor (); Executor.submit (()-{String ThreadName=Thread.CurrentThread (). GetName (); System.out.println ("Hello" +threadname); }); Try{System.out.println ("Attempt to shutdown executor"); Executor.shutdown (); Executor.awaittermination (5, Timeunit.seconds); } Catch(interruptedexception e) {System.err.println ("Tasks Interrupted"); } finally { if(!executor.isterminated ()) {System.err.println ("Cancel non-finished Tasks"); } executor.shutdownnow (); System.out.println ("Shutdown finished"); } }}
Executors also supports another type of task: callable. Callable will return a value.
Importjava.util.concurrent.*; Public classcallable{ Public Static voidMain (string[] args)throwsillegalstateexception,interruptedexception, executionexception{callable<Integer> task = () {
Try{TimeUnit.SECONDS.sleep (1); return123; } Catch(interruptedexception e) {Throw NewIllegalStateException ("Task Interrupted", E); } }; Executorservice Executor= Executors.newfixedthreadpool (1); Future<Integer> future =Executor.submit (Task); System.out.println ("Future done?" +Future.isdone ()); Integer Res=Future.get (); System.out.println ("Future done?" +Future.isdone ()); System.out.print ("Result:" +res); Executor.shutdownnow (); }}
Executors can submit multiple callable tasks in bulk at once through InvokeAll ().
Importjava.util.concurrent.*;ImportJava.util.*; Public classmorecallable{ Public Static voidMain (string[] args)throwsinterruptedexception{Executorservice Executor=Executors.newworkstealingpool (); List<Callable<String>> Callables =arrays.aslist (()"Task1", () "Task2", () "Task3"); Executor.invokeall (callables). Stream (). Map ( Future- { Try{ returnFuture.get (); }Catch(Exception e) {Throw NewIllegalStateException (e); }}). ForEach (System.out::p rintln); }}
-----
Executors is a class that contains a lot of static methods, which can be used as a tool class when used.
Executors.newworkstealingpool () This method is then dragged out of a class: Forkjoinpool (extends Abstractexecutorservice (since 1.7))
Subsequent continuation of the write Future,forkjoinpool and thread scheduling: Scheduledexecutorservice.
Reference:
Http://www.open-open.com/lib/view/open1431307471966.html
Https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/package-summary.html
Http://www.cnblogs.com/lucky_dai/p/5509261.html
Java source Code
Java Multithreaded---thread Runnable executors