Home Java JavaBase What are the three ways to create threads in java?

What are the three ways to create threads in java?

Nov 23, 2020 pm 04:51 PM
java Create thread

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.

What are the three ways to create threads in java?

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

public class MyThread extends Thread{//继承Thread类
  public void run(){
  //重写run方法
  }
}
public class Main {
  public static void main(String[] args){
    new MyThread().start();//创建并启动线程
  }
}

------------------ ------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:

public class MyThread2 implements Runnable {//实现Runnable接口
  public void run(){
  //重写run方法
  }
}
public class Main {
  public static void main(String[] args){
    //创建并启动线程
    MyThread2 myThread=new MyThread2();
    Thread thread=new Thread(myThread);
    thread().start();
    //或者    new Thread(new MyThread2()).start();
  }
}

------------------------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:

public class Main {
  public static void main(String[] args){
   MyThread3 th=new MyThread3();
   //使用Lambda表达式创建Callable对象
     //使用FutureTask类来包装Callable对象
   FutureTask<Integer> future=new FutureTask<Integer>(
    (Callable<Integer>)()->{
      return 5;
    }
    );
   new Thread(task,"有返回值的线程").start();//实质上还是以Callable对象来创建并启动线程
    try{
    System.out.println("子线程的返回值:"+future.get());//get()方法会阻塞,直到子线程执行结束才返回
    }catch(Exception e){
    ex.printStackTrace();
   }
  }
}

------------------------ -------------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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1502
276
How to handle transactions in Java with JDBC? How to handle transactions in Java with JDBC? Aug 02, 2025 pm 12:29 PM

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

How to work with Calendar in Java? How to work with Calendar in Java? Aug 02, 2025 am 02:38 AM

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Aug 04, 2025 pm 12:48 PM

Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste,

Understanding Network Ports and Firewalls Understanding Network Ports and Firewalls Aug 01, 2025 am 06:40 AM

Networkportsandfirewallsworktogethertoenablecommunicationwhileensuringsecurity.1.Networkportsarevirtualendpointsnumbered0–65535,withwell-knownportslike80(HTTP),443(HTTPS),22(SSH),and25(SMTP)identifyingspecificservices.2.PortsoperateoverTCP(reliable,c

How does garbage collection work in Java? How does garbage collection work in Java? Aug 02, 2025 pm 01:55 PM

Java's garbage collection (GC) is a mechanism that automatically manages memory, which reduces the risk of memory leakage by reclaiming unreachable objects. 1.GC judges the accessibility of the object from the root object (such as stack variables, active threads, static fields, etc.), and unreachable objects are marked as garbage. 2. Based on the mark-clearing algorithm, mark all reachable objects and clear unmarked objects. 3. Adopt a generational collection strategy: the new generation (Eden, S0, S1) frequently executes MinorGC; the elderly performs less but takes longer to perform MajorGC; Metaspace stores class metadata. 4. JVM provides a variety of GC devices: SerialGC is suitable for small applications; ParallelGC improves throughput; CMS reduces

Using HTML `input` Types for User Data Using HTML `input` Types for User Data Aug 03, 2025 am 11:07 AM

Choosing the right HTMLinput type can improve data accuracy, enhance user experience, and improve usability. 1. Select the corresponding input types according to the data type, such as text, email, tel, number and date, which can automatically checksum and adapt to the keyboard; 2. Use HTML5 to add new types such as url, color, range and search, which can provide a more intuitive interaction method; 3. Use placeholder and required attributes to improve the efficiency and accuracy of form filling, but it should be noted that placeholder cannot replace label.

Comparing Java Build Tools: Maven vs. Gradle Comparing Java Build Tools: Maven vs. Gradle Aug 03, 2025 pm 01:36 PM

Gradleisthebetterchoiceformostnewprojectsduetoitssuperiorflexibility,performance,andmoderntoolingsupport.1.Gradle’sGroovy/KotlinDSLismoreconciseandexpressivethanMaven’sverboseXML.2.GradleoutperformsMaveninbuildspeedwithincrementalcompilation,buildcac

go by example defer statement explained go by example defer statement explained Aug 02, 2025 am 06:26 AM

defer is used to perform specified operations before the function returns, such as cleaning resources; parameters are evaluated immediately when defer, and the functions are executed in the order of last-in-first-out (LIFO); 1. Multiple defers are executed in reverse order of declarations; 2. Commonly used for secure cleaning such as file closing; 3. The named return value can be modified; 4. It will be executed even if panic occurs, suitable for recovery; 5. Avoid abuse of defer in loops to prevent resource leakage; correct use can improve code security and readability.

See all articles