In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces the relevant knowledge of "what are the implementation methods of Java multithreading". The editor shows you the operation process through an actual case, the operation method is simple and fast, and it is practical. I hope this article "what are the implementation methods of Java multithreading" can help you solve the problem.
I. Preface
The three ways to realize Java multithreading are inheriting Thread class, implementing Runnable interface, and using ExectorService, Callable and Future to realize multithreading with returned results. In the first two ways, the thread has no return value after execution, and only the last one has a return value.
Second, inheriting the Thread class to implement multithreading
1.Thread is essentially 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 2.start () method is a native method that starts a new thread and executes the run () method
3. Multithreading is easy to implement in this way. By directly extend Thread your own class and overriding the run () method, you can start a new thread and execute the self-defined run () method.
Class MyThread extends Thread {public void run () {System.out.println ("My Thread.run ()");}}
Start the thread:
MyThread myThread1 = new MyThread (); myThread1.start (); III. Runnable interface to achieve multithreading
There is always a single inheritance limitation for inheritance in Java programs. If your own class has already extends another class, it is impossible to provide a second multi-threaded principal definition structure in extends Thread,Java: implementing the java.lang.Runnable interface.
Definition:
@ FunctionalInterface / / after introducing the Lambda expression from JDK1.8, it becomes the functional interface public interface Runnable {public void run ();}
Implement a Runnable interface:
Public class MyThread extends OtherClass implements Runnable {public void run () {System.out.println ("MyThread.run ()");}}
To start MyThread, first instantiate a Thread and pass in your own MyThread instance:
MyThread myThread = new MyThread (); Thread thread = new Thread (myThread); thread.start ()
When a Runnable target parameter is passed to Thread, the run () method of Thread calls target.run ()
Public void run () {if (target! = null) {target.run ();}} IV, the relationship between Thread and Runnable
1. From the point of view of the structure of the code itself, it is certainly the most convenient to use Runnable, because it can avoid the limitation of single inheritance and better expand the function.
two。 Structural observation of the relationship between Thread and Runnable
The public class Thread extends Object implements Runnable {} Thread class is also a subclass of the Runnable interface, so when you inherited the Thread class, you actually overridden the Runnable method.
3. When Thread starts multithreading, the start () method is called, and then the run () method is found. When a Runnable interface object is passed through the constructor of the Thread class, the interface object is saved by the property of target in Thread, and the run method of the Thread class is called when the start () method is executed, and this run () method invokes the overridden run () method of the Runnable interface subclass.
The essence of multithreaded development is that multiple threads can preempt unified resources, so Thread mainly describes threads, then the description of resources is completed through Runnable.
Fifth, use ExecutorService, Callable and Future to implement multithreading with returned results
1.ExecutorService, Callable and Future are actually functional classes in the Executor framework.
two。 Tasks that return values must implement the Callable interface; similarly, tasks that do not return values must implement the Runnable interface
3. After executing the Callable task, you can get an object of Future, on which you can call get to get the Object returned by the Callable task. Combined with the thread pool interface ExecutorService, you can realize multithreading with returned results.
The Runnable interface has a disadvantage: when the thread finishes executing, we cannot get a return value, so we propose a new thread implementation interface: java.util.concurrent.Callable interface after JDK1.5.
@ FunctionalInterfacepublic interface Callable {public V call () throws Exception;}
When Callbale is defined, you can set a generic type. The type of this generic type is the type that returns data.
The Callable interface is similar to the Runnable interface, but what needs to be implemented is the call method, and we can see from the above code that the task performed by the run () method has no return value, but the call method has a return value, and you can customize the type of the return value, which is the biggest difference between the two interfaces.
Example:
Import java.util.concurrent.*;import java.util.Date;import java.util.List;import java.util.ArrayList; / * Threads with return values * / @ SuppressWarnings ("unchecked") public class Test {public static void main (String [] args) throws ExecutionException, InterruptedException {System.out.println ("- the program starts running -"); Date date1 = new Date () Int taskSize = 5; / / create a thread pool ExecutorService pool = Executors.newFixedThreadPool (taskSize); / / create multiple tasks with return values List list = new ArrayList (); for (int I = 0; I
< taskSize; i++) { Callable c = new MyCallable(i + " "); // 执行任务并获取Future对象 Future f = pool.submit(c); // System.out.println(">> > "+ f.get () .toString (); list.add (f);} / / close thread pool pool.shutdown () / / get the running results of all concurrent tasks for (Future f: list) {/ / get 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 ends running -, program run time [" + (date2.getTime ()-date1.getTime ()) + "millisecond]");}} class MyCallable implements Callable {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 + "the task returns the running result, and the current task time [" + time + "millisecond]";}} "what are the ways to implement Java multithreading"? thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.