Several ways to implement multi-threading in Java
1) Inherit the Thread class
Steps to implement:
- 1) Create a subclass of Thread class
- 2) Rewrite the run method
- 3) Create thread object
- 4) Start the thread
Code example:
package ; public class ThreadDemo02 { /** * The first way to implement threads * Implemented by creating a subclass of Thread class * @param args */ public static void main(String[] args) { ("The main method executed 1..."); // Threads in Java are essentially a Thread object Thread t1 = new ThreadTest01(); // Start a new thread (); for(int i = 0 ; i< 100 ; i++){ ("Loop of main method..."+i); } ("The main method execution ended 3..."); } }
/** * The first custom thread class * Inherit Thread parent class * Rewrite the run method */ class ThreadTest01 extends Thread{ @Override public void run() { ("Our first thread executed 2..."); for(int i = 0 ; i < 10 ; i ++){ ("Subthread:"+i); } } }
Note:
1) Starting the thread uses the start method instead of the run method
2) The thread cannot be started multiple times. If you want to create multiple threads, you need to create multiple Thread objects.
2) Implement the Runnable interface
In the first implementation method, we encapsulate the business of thread creation and thread execution in the Thread object. We can effectively separate thread program code and data through the Runable interface.
Steps to implement:
- 1) Create a Runable implementation class
- 2) Rewrite the run method
- 3) Create Runable instance object (implemented by implementing the class)
- 4) Create a Thread object and use the Runable instance created in the third step as a parameter of the Thread constructor
- 5) Start the thread
Code example:
package ; public class RunableDemo01 { /** * The second way to thread * The essence is to pass a Runable interface implementation when creating Thread object * @param args */ public static void main(String[] args) { ("main executed..."); // Create a new thread Thread object Runnable r1 = new RunableTest(); Thread t1 = new Thread(r1); // Start the thread (); ("Main is over..."); } } /** * The second way to create threads * Create a Runable interface implementation class */ class RunableTest implements Runnable{ @Override public void run() { ("The child thread has been executed..."); } }
Benefits of implementing Runable interface:
1) Can avoid the limitations caused by single-inheritance of Java
2) Suitable for multiple identical program codes to handle the same resource, effectively separate threads and program codes and data, which better reflects the object-oriented design idea
3) Implement Callable interface (JDK1.5>=)
The two ways to create threads we introduced earlier are to override the run method, and the run method does not return the result, that is, the main method does not know when the opened thread starts execution and when it ends execution, and cannot obtain the corresponding return result. Moreover, the run method cannot throw possible exceptions.
After JDK1.5, a new thread was created by implementing the Callable interface, which can obtain the corresponding return result.
Code example:
package ; import ; import ; public class CallableDemo01 { /** * The third way to create threads: * Callable method */ public static void main(String[] args) throws Exception { // Create a Callable instance Callable<Integer> callable = new MyCallable(); FutureTask<Integer> futureTask = new FutureTask<>(callable); // Get a thread. You must first create a Thread object. FutureTask is essentially an implementation of the Runable interface. Thread t1 = new Thread(futureTask); ("main method start..."); (); // In essence, it is still the run method in Runable, but the run method calls the call method. // Get the returned result (()); // Get the result returned after the enabled thread is executed ("main method end..."); } } /** * Create a Callable implementation class * We need to specify the generic of Callable, which is the type that returns the result. */ class MyCallable implements Callable<Integer>{ /** * Methods that will be executed automatically after the thread is * @return * @throws Exception */ @Override public Integer call() throws Exception { int sum = 0; for(int i = 1 ; i <= 100 ; i ++){ sum += i; } return sum; } }
The difference between implementing the Runnable interface and implementing the Callable interface:
- 1) Runnable has been available since java 1.1, and Callable has been added after 1.5.
- 2) The method specified by Callable is call(), and the method specified by Runnable is run()
- 3) The Callable task can return the value after execution, while the Runnable task cannot return the value (it is void)
- 4) The call method can throw an exception, but the run method cannot
- 5) Run the Callable task and you can get a Future object, representing the result of asynchronous calculations. It provides a method to check whether the calculation is completed, to wait for the calculation to be completed, and to retrieve the results of the calculation. Through the Future object, you can understand the task execution status, cancel the task execution, and obtain the execution results.
4) Creating thread pool method
Join the thread pool to run, Runnable uses the execute method of ExecutorService, and Callable uses the submit method.
In fact, the underlying implementation of the Callable interface is to encapsulate the Runable interface implementation. The thread starts and executes the run method in the Runable interface implementation, but the call method is called in the run method.
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.