Three ways to implement Java multithreading

Source: Internet
Author: User
Tags date1

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 threads after the thread has finished running, only the last one with the return value.


1, inherit the thread class to realize multithreading
The method of inheriting the thread class is listed by me as a multithreaded implementation, but thread essentially implements an instance of 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. It will start a new thread. and runs the Run () method.

This way of implementing multithreading is very easy, by extend thread directly through your own class, and by copying the run () method, you can start a new thread and run a custom run () method. Like what:

public class MyThread extends Thread {public void run () {System.out.println ("Mythread.run ()"); }}
Start the thread in the appropriate place such as the following:
MyThread myThread1 = new MyThread (); MyThread myThread2 = new MyThread (); Mythread1.start (); Mythread2.start ();

2, realize the Runnable interface way to realize multithreading
Assuming that your class already extends a class, you cannot directly extends the Thread, at which point you must implement a runnable interface, such as the following:
public class MyThread extends Otherclass implements Runnable {public void run () {System.out.println ("Mythread.run ()")  ; }}
In order to start mythread, you need to instantiate a thread first and pass in your own Mythread instance:
MyThread MyThread = new MyThread (); Thread thread = new Thread (myThread); Thread.Start ();
In fact. When a runnable target parameter is passed to the thread. The thread's run () method calls Target.run () and references the JDK source code:
public void Run () {if (target! = null) {Target.run (); }}

3, the use of Executorservice, callable, the future to achieve a return result of multi-threading
Executorservice, callable, future This object is actually a function class in the executor framework. You want to know more about the executor framework's access to http://www.javaeye.com/topic/366591. There is a very specific explanation for this framework. The thread that returns the result is a new feature introduced in JDK1.5, which is really useful, 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. Similar to. A task that has no return value must runnable the interface. After running the callable task, be able to get a future object, call get on the object can get to the callable task returned object, and combined with thread pool interface Executorservice can realize the legend has the return result of multithreading. An example of a complete multithreaded sample with returned results is provided below. Verified under JDK1.5 No problem can be used directly. The code is as follows:

Import Java.util.concurrent.*;import java.util.date;import Java.util.list;import java.util.arraylist;/*** has a return value for the thread */ @SuppressWarnings ("Unchecked") public class Test {public static void main (string[] args) throws Executionexception, Inte   rruptedexception {System.out.println ("----program starts execution----");   Date date1 = new Date ();   int tasksize = 5;   Create a thread pool executorservice pool = Executors.newfixedthreadpool (tasksize);   Create multiple tasks with return values list<future> List = new arraylist<future> ();    for (int i = 0; i < tasksize; i++) {callable c = new Mycallable (i + "");    Run the task and get the Future object F = Pool.submit (c);    System.out.println (">>>" + f.get (). toString ());   List.add (f);   }//Close thread pool Pool.shutdown (); Gets the execution result for all concurrent tasks for (f:list) {//Gets the return value of the task from the future object and outputs it to console System.out.println (">>>" + f.get ()   . toString ());   } Date Date2 = new Date (); SYSTEM.OUT.PRINTLN ("----program End execution----, program execution Time" "+ (Date2.gettime ()-Date1.gettime ()) + "milliseconds" ");}} Class Mycallable implements callable<object> {private String tasknum; Mycallable (String tasknum) {this.tasknum = Tasknum;}   Public Object Call () throws Exception {System.out.println (">>>" + tasknum + "task start");   Date DATETMP1 = new Date ();   Thread.Sleep (1000);   Date DATETMP2 = new Date ();   Long time = Datetmp2.gettime ()-datetmp1.gettime ();   System.out.println (">>>" + tasknum + "task termination"); return tasknum + "task return execution result, current task time" "+" "" "" "
Code Description:
The executors class is in the code above. Provides a series of factory methods for creating a first thread pool. 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 ()
Creates a cacheable pool of threads. Calling execute reuses the previously constructed thread (assuming the thread is available).

Assuming that an existing thread is not available, a new thread is created and joined 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)
Create a thread pool that supports timed and recurring task runs. In most cases it can be used to replace the timer class.



Executoreservice provides the submit () method, passing a callable, or runnable, back to the future. Suppose the executor backend thread pool has not finished callable calculation. This call returns the Get () method of the future object. will block until the calculation is complete.

Reproduced in: http://www.cnblogs.com/yezhenhan/archive/2012/01/09/2317636.html


Three ways to implement Java 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.