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.
Reproduced in: http://www.cnblogs.com/yezhenhan/archive/2012/01/09/2317636.html
How many java threads can be implemented?
There are three types:
(1) inherit the Thread class and override the run Function
Create:
Class xx extends Thread {
Public void run (){
Thread. sleep (1000) // The Thread slews for 1000 milliseconds. sleep enables the Thread to enter the Block state and releases resources.
}}
Enable thread:
Object. start () // start thread, run Function
(2) Implement the Runnable interface and rewrite the run function.
Enable thread:
Thread t = new Thread (object) // create a Thread object
T. start ()
(3) Implement the Callable interface and rewrite the call function.
Callable is similar to Runnable interfaces. The classes that implement Callable interfaces and Runnable classes are all tasks that can be executed by other threads.
The differences between Callable and Runnable are as follows:
① Callable specifies the call () method, while Runnable specifies the run () method ().
② Callable tasks can return values after execution, while Runnable tasks cannot return values.
③ The call () method can throw an exception, while the run () method cannot throw an exception.
④ Run the Callable task to get a Future object. Future indicates the result of asynchronous calculation. It provides methods to check whether the computing is complete, and so on.
After the calculation is completed, the calculation result is retrieved. The Future object can be used to understand the task execution status, cancel the task execution, and obtain the task execution result.
How can I implement multithreading in Java?
1.
Public class AAA extends Thread {
Public void run (){
}
}
2. public class BBB implements Runnable {
Public void run (){}
}