1. How to implement Java multithreading
There are three main ways to implement Java Multithreading:
- Inherit the thread class
- Implementing the Runnable Interface
- Use Executorservice, callable, and future to implement multithreading with return results.
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 extends 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 MyThread extends Thread {
public void Run () {
System.out.println ("Mythread.run ()");
}
}
Start the thread in the appropriate place as follows:
MyThread myThread1 = new MyThread ();
MyThread myThread2 = 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
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 ()
Refer to the JDK source code:
public void Run () {
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 implement the Runnable 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:
Import Java.util.concurrent.*;import java.util.date;import java.util.list;import java.util.arraylist;/** * Java thread: Thread with return value * */@SuppressWarnings ("Unchecked") public class Test {public static void main (string[] args) throws Executionexception, interruptedexception {System.out.println ("----program starts running----");D ate 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 + "");//Perform task and get future object Fu Ture f = pool.submit (c);//System.out.println (">>>" + f.get (). toString ()); List.add (f);} Close the thread pool Pool.shutdown ();//Gets the run result for all concurrent tasks for (the future f:list) {//Gets the return value of the task from the future object and outputs it to the console System.out.println ("> >> "+ f.get (). toString ());} Date Date2 = new Date (); SYSTEM.OUT.PRINTLN ("----program ends running----, program run Time" "+ (Date2.gettime ()-date1.gettime ()) +" milliseconds "");}} Class Mycallable implements callable<object> {privateString Tasknum; Mycallable (String tasknum) {this.tasknum = Tasknum;} Public Object Call () throws Exception {System.out.println (">>>" + tasknum + "task start");D ate dateTmp1 = new Date (); Thread.Sleep (;D ate dateTmp2 = new Date (), Long time = Datetmp2.gettime ()-datetmp1.gettime (); System.out.println (">>>" + tasknum + "task termination"), return Tasknum + "task return run result, current task time" "+" "+" "";}}
Code Description:
The executors class in the code above provides a series of factory methods for creating a 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 ()
Creates 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)
Create a thread pool that supports timed and recurring task executions, which in most cases can be used to replace the timer class.
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.
Three ways to implement Java multi-threading