Java Multi-line Cheng

Source: Internet
Author: User
Tags date1

Recently in the code optimization to learn and study the use of the next Java multi-threading, see the Novice's insights after doing a summary.
1.JAVA Multithreading Implementation Mode
Java Multi-threaded implementation of the main three kinds: inherit the thread class, implement Runnable interface, use Executorservice, callable, the future implementation has the result of multithreading. There are no return values for the first two methods after the thread has finished executing, only the last one with the return value.

2. Inheriting the thread class for multithreading
Methods of inheriting the thread class although I am listed as a multithreaded implementation, thread is essentially an instance of implementing the Runnable interface, which represents an instance of a thread, and the only way to start a thread is through the start () instance method of the thread class. The start () method is a native method that starts a new thread and executes the run () method. This way of implementing multithreading is simple, by extend thread directly through your own class, and by copying the run () method, you can start a new thread and execute your own defined run () method. For example:

 Public class extends Thread {  publicvoid  run () {System.out.println ("Mythread.run ()"New new MyThread (); Mythread1.start (); Mythread2.start ();  

3. Implement runnable interface mode to realize multithreading
If your class already extends another class, you cannot directly extends the Thread, at which point you must implement a runnable interface, as follows:

 Public classMyThreadextendsOtherclassImplementsRunnable { Public voidrun () {System.out.println ("Mythread.run ()"); }} In order to start MyThread, you need to instantiate a thread first and pass in your MyThread instance: MyThread MyThread=NewMyThread (); Thread Thread=Newthread (myThread); Thread.Start (); In fact, when a runnable target parameter is passed to the thread, the thread's Run () method calls Target.run (). Refer to the JDK source code: Public voidrun () {if(Target! =NULL) {target.run (); }}

4. Use Executorservice, callable, and future to implement multi-threading with return results
Executorservice, callable, future This object is actually a function class in the executor framework. To learn more about the accessible http://www.javaeye.com/topic/366591 of the executor framework, here is a detailed explanation of the framework. The thread that returns the result is a new feature introduced in JDK1.5, and it's really practical, and with this feature I don't have to go any further to get the return value, and it can be flawed even if it's done.
A task that can return a value must implement the callable interface, and similarly, a task that has no return value must runnable the interface. After performing the callable task, you can get a future object, call get on the object to get to the callable task returned object, and combined with the thread pool interface Executorservice can realize the legend has the return result of multithreading. Here is a complete example of a multithreaded test with return results, which can be used directly under JDK1.5. The code is as follows:

Importjava.util.concurrent.*;Importjava.util.Date;Importjava.util.List;Importjava.util.ArrayList;/*** Java thread: Thread with return value * *@authorwb_qiuquan.ying*/@SuppressWarnings ("Unchecked") Public classTest { Public Static voidMain (string[] args)throwsexecutionexception, interruptedexception {System.out.println ("----program starts running----"); Date Date1=NewDate (); intTasksize = 5; //Create a pool of threadsExecutorservice pool =Executors.newfixedthreadpool (tasksize); //Create multiple tasks with return valueslist<future> list =NewArraylist<future>();  for(inti = 0; i < tasksize; i++) {callable C=NewMycallable (i + "")); //perform tasks and get future objectsFuture F =Pool.submit (c); //System.out.println (">>>" + f.get (). toString ());List.add (f); }   //Close the thread poolPool.shutdown (); //get run results for all concurrent tasks    for(Future f:list) {//gets the return value of the task from the future object and outputs it to the consoleSystem.out.println (">>>" +f.get (). toString ()); } Date date2=NewDate (); System.out.println ("----program End run----, program run Time" "+ (Date2.gettime ()-date1.gettime ()) +" MS "");}}classMycallableImplementsCallable<object> {PrivateString Tasknum; Mycallable (String tasknum) { This. Tasknum =Tasknum;} PublicObject Call ()throwsException {System.out.println (">>>" + tasknum + "task Start"); Date DATETMP1=NewDate (); Thread.Sleep (1000); Date DATETMP2=NewDate (); LongTime = Datetmp2.gettime ()-Datetmp1.gettime (); System.out.println (">>>" + tasknum + "task termination"); returnTasknum + "task returns run result, current task time" "+" + "millisecond" ";}}

code description:
The above code executors class, A series of factory methods are provided to create a first thread pool, and the returned thread pool implements the Executorservice interface.
public static executorservice newfixedthreadpool (int nthreads)  
Creates a thread pool of a fixed number of threads.
public static Executorservice Newcachedthreadpool ()  
Span style= "font-size:15px;" > Create a cacheable thread pool that calls execute to reuse previously constructed threads if the threads are available. If an existing thread is not available, a new thread is created and added to the pool. Terminates and removes from the cache those threads that have not been used for 60 seconds.
public static Executorservice Newsinglethreadexecutor ()  
Create a single-threaded executor.
public static scheduledexecutorservice newscheduledthreadpool (int corepoolsize)  

Executoreservice provides the submit () method, passing a callable, or runnable, back to the future. If the executor background thread pool has not completed the calculation of callable, this call returns the Get () method of the future object, blocking until the calculation is complete.

Transfer from link

Java Multi-line Cheng

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.