Java multi-thread implementation in three ways, java multi-thread in three ways
JAVA multithreading has three main implementation methods: Inheriting the Thread class, implementing the Runnable interface, and implementing multiple threads with returned results using ExecutorService, Callable, and Future. The first two methods do not return values after the thread is executed. The last method only includes the returned values.
1. inherit the Thread class to implement Multithreading
Although the method that inherits the Thread class is listed as a multi-threaded implementation method, Thread is essentially an instance that implements the Runnable interface. It represents a Thread instance, 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 runs the run () method. Multithreading is easy to implement in this way. You can use your own class to directly extend the Thread and re-write the run () method to start a new Thread and execute the self-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();
2. implement multiple threads through the Runnable interface
If your class has extends another class, you cannot directly extends Thread. At this time, you must implement a Runnable interface, as shown below:
public class MyThread extends OtherClass implements Runnable { public void run() { System.out.println("MyThread.run()"); } }
To start MyThread, you must first instantiate a Thread and input your own MyThread instance:
MyThread myThread = new MyThread(); Thread thread = new Thread(myThread); thread.start();
In fact, after passing in a Runnable target parameter to the Thread, the Thread's run () method will call target. run (). Refer to the JDK source code:
public void run() { if (target != null) { target.run(); } }
3. ExecutorService, Callable, and Future are used to implement multiple threads with returned results.
ExecutorService, Callable, and Future objects are actually functional classes in the Executor framework. To learn more about the Executor framework, visit the http://www.javaeye.com/topic/366591, which is explained in detail here. The thread that returns the result is a new feature introduced in JDK1.5, which is indeed very practical. With this feature, I don't need to take a long time to get the returned value, and even if it is implemented, it may be exposed.
The Callable interface must be implemented for a task that can return values. Similarly, a task without a return value must be a Runnable interface. After executing the Callable task, you can get a Future Object. On this Object, you can call get to get the Object returned by the Callable task, combined with the thread pool interface ExecutorService, You can implement multiple threads with returned results. The following provides a complete multi-threaded test example with returned results. It can be directly used if it has been verified in JDK. The Code is as follows:
Import java. util. concurrent. *; import java. util. date; import java. util. list; import java. util. arrayList;/*** threads with returned values */@ SuppressWarnings ("unchecked") public class Test {public static void main (String [] args) throws ExecutionException, InterruptedException {System. out. println ("---- program starts running ----"); Date date1 = new Date (); int taskSize = 5; // create a thread pool ExecutorService pool = Executors. newFixedThreadPool (taskSize); // create multiple task lists with returned values <Future> List = new ArrayList <Future> (); for (int I = 0; I <taskSize; I ++) {Callable c = new MyCallable (I + ""); // execute the task and obtain the Future object Future f = pool. submit (c); // System. out. println (">>>" + f. get (). toString (); list. add (f);} // close the thread pool. shutdown (); // obtain the running result of all concurrent tasks for (Future f: list) {// obtain the return value of the task from the Future object and output it to the console System. out. println (">>>" + f. get (). toString ();} Date date2 = new Date (); System. out. println ("---- program stops running ----, program running time [" + (date2.getTime ()-date1.getTime () + "millisecond ]");}} 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 + ""); return taskNum + "The task returns the running result. The current task time is [" + time + "millisecond ]";}}
Code Description:
In the code above, the Executors class provides a series of factory methods for creating the first thread pool, and the returned thread pool implements the ExecutorService interface.
Public static ExecutorService newFixedThreadPool (int nThreads)
Creates a thread pool with a fixed number of threads.
Public static ExecutorService newCachedThreadPool ()
Create a cache-able thread pool. Calling execute will reuse previously constructed threads (if the thread is available ). If the existing thread is not available, create a new thread and add it to the pool. Terminate and Remove unused threads from the cache for 60 seconds.
Public static ExecutorService newSingleThreadExecutor ()
Create a single-threaded Executor.
Public static ScheduledExecutorService newScheduledThreadPool (int corePoolSize)
Create a thread pool that supports scheduled and periodic task execution. In most cases, it can be used to replace the Timer class.
ExecutoreService provides the submit () method to pass a Callable or Runnable, and returns the Future. If the Executor background thread pool has not completed Callable calculation, this call returns the get () method of the Future object, blocking until the calculation is complete.
I have a public account that will often share some Java-related things. If you like it, you can search for "Java headers" or "javatuanzhang.