What are the three ways to create threads in java?
The three ways to create threads in Java are: 1. Inherit the Thread class to create a thread; 2. Implement the Runnable interface to create a thread; 3. Use Callable and Future to create a thread.
Java uses the Thread class to represent threads, and all thread objects must be instances of the Thread class or its subclasses. Java can create threads in three ways, as follows:
1) Inherit the Thread class to create threads
2) Implement the Runnable interface Create threads
3) Use Callable and Future to create threads
Let us look at these three methods of creating threads respectively.
------------------------Inherit the Thread class to create a thread------ ---------------
The general steps to create and start multi-threads by inheriting the Thread class are as follows
1]D define a subclass of the Thread class, and override the run() method of the class. The method body of this method is the task that the thread needs to complete, and the run() method is also Called the thread execution body.
#2] Create an instance of the Thread subclass, that is, create a thread object
3] Start the thread, that is, call the thread's start()Method
Code example
1 2 3 4 5 6 7 8 9 10 |
|
------------------ ------Implement Runnable interface to create threads---------------------
By implementing Runnable The general steps for creating and starting a thread through an interface are as follows:
#1] Define the implementation class of the Runnable interface, and also override the run() method. This run() method is the same as the run() in Thread. ) method is also the execution body of the thread
#2] Create an instance of the Runnable implementation class, and use this instance as the target of Thread to create a Thread object. This Thread object is the real thread object.
3】The third part still starts the thread by calling the start() method of the thread object
Code example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
------------------------Use Callable and Future to create threads------------- -------
is different from the Runnable interface. The Callable interface provides a call() method as the thread execution body. The call() method is The run() method must be powerful.
》The call() method can have a return value
》The call() method can declare that it throws an exception
Java5 provides the Future interface to represent the return value of the call() method in the Callable interface, and provides an implementation class FutureTask for the Future interface. This implementation class not only implements the Future interface, but also implements the Runnable interface, so Can be used as the target of the Thread class. Several public methods are defined in the Future interface to control its associated Callable tasks.
>boolean cancel(boolean mayInterruptIfRunning): View cancels the Callable task associated with the Future
>V get(): Returns the return value of the call() method in Callable, call this The method will cause the program to block, and the return value will not be obtained until the sub-thread ends.
>V get(long timeout, TimeUnit unit): Returns the return value of the call() method in Callable, blocking for up to timeout time , no return is thrown after the specified time. TimeoutException
>boolean isDone(): If the Callable task is completed, it returns True
>boolean isCancelled(): If it is canceled before the Callable task is completed normally. Cancel, return True
After introducing related concepts, the steps to create and start a thread with a return value are as follows:
1】Create an implementation class of the Callable interface and implement call () method, and then create an instance of the implementation class (starting from java8, you can directly use Lambda expressions to create Callable objects).
2] Use the FutureTask class to wrap the Callable object. The FutureTask object encapsulates the return value of the call() method of the Callable object.
3 】Use the FutureTask object as the target of the Thread object to create and start the thread (because FutureTask implements the Runnable interface)
#4】Call the get() method of the FutureTask object to obtain the result after the execution of the sub-thread. Return value
Code example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
------------------------ -------------Comparison of three methods of creating threads---------------------------------- -------
The ways to implement Runnable and the Callable interface are basically the same, except that the latter has a return value when executing the call() method, and the latter has no return value when the thread execution body run() method Return value, so these two methods can be classified into one. The difference between this method and the method inheriting the Thread class is as follows:
1. Потоки реализуют только интерфейс Runnable или Callable, а также могут наследовать другие классы.
2. Таким образом, несколько потоков могут совместно использовать целевой объект, что очень удобно для ситуаций, когда несколько потоков обрабатывают один и тот же ресурс.
3. Однако программирование немного сложное. Если вам нужно получить доступ к текущему потоку, вы должны вызвать метод Thread.currentThread().
4. Класс потока, который наследует класс Thread, не может наследовать от других родительских классов (определяется единым наследованием Java).
Примечание. Обычно рекомендуется создавать многопотоки путем реализации интерфейсов.
Для получения дополнительной информации о программировании посетите: Видеокурс по программированию! !
The above is the detailed content of What are the three ways to create threads in java?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics





Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.
