国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home Java Javagetting Started 3 ways to create threads in Java and their differences

3 ways to create threads in Java and their differences

Nov 26, 2019 pm 05:19 PM
java thread

How to create a thread in java? The following article will introduce to you 3 ways to create threads and their differences. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

3 ways to create threads in Java and their differences

If you want to create a thread in java, there are generally three methods:

1. Inherit the Thread class;

2. Implement the Runnable interface;

3. Use Callable and Future to create threads.

[Recommended learning: java video tutorial]

1. Inherit the Thread class

Inheritance For the Thread class, you must override the run method and define the tasks that need to be performed in the run method.

class?MyThread?extends?Thread{
????private?static?int?num?=?0;
?????
????public?MyThread(){
????????num++;
????}
?????
????@Override
????public?void?run()?{
????????System.out.println("主動創(chuàng)建的第"+num+"個線程");
????}
}

After creating your own thread class, you can create a thread object, and then start the thread through the start() method. Note that the run() method is not called to start the thread. The run method only defines the tasks that need to be performed. If the run method is called, it is equivalent to executing the run method in the main thread. There is no difference from ordinary method calls. At this time, there is no A new thread will be created to perform the defined tasks.

public?class?Test?{
????public?static?void?main(String[]?args)??{
????????MyThread?thread?=?new?MyThread();
????????thread.start();
????}
}
?
?
class?MyThread?extends?Thread{
????private?static?int?num?=?0;
?????
????public?MyThread(){
????????num++;
????}
?????
????@Override
????public?void?run()?{
????????System.out.println("主動創(chuàng)建的第"+num+"個線程");
????}
}

In the above code, by calling the start() method, a new thread will be created. In order to distinguish the difference between start() method call and run() method call, please look at the following example:

public?class?Test?{
????public?static?void?main(String[]?args)??{
????????System.out.println("主線程ID:"+Thread.currentThread().getId());
????????MyThread?thread1?=?new?MyThread("thread1");
????????thread1.start();
????????MyThread?thread2?=?new?MyThread("thread2");
????????thread2.run();
????}
}
?
?
class?MyThread?extends?Thread{
????private?String?name;
?????
????public?MyThread(String?name){
????????this.name?=?name;
????}
?????
????@Override
????public?void?run()?{
????????System.out.println("name:"+name+"?子線程ID:"+Thread.currentThread().getId());
????}
}

Run result:

From the output result The following conclusions can be drawn:

1) The thread IDs of thread1 and thread2 are different, and the ID of thread2 and the main thread are the same, indicating that calling the run method does not create a new thread, but runs directly in the main thread. The run method is no different from ordinary method calls;

2) Although the start method call of thread1 is called before the run method of thread2, the information related to the run method call of thread2 is output first, indicating that the new The process of thread creation will not block subsequent execution of the main thread.

2. Implement the Runnable interface

In addition to inheriting the Thread class when creating a thread in Java, you can also achieve something similar by implementing the Runnable interface function. Implementing the Runnable interface must override its run method.

The following is an example:

public?class?Test?{
????public?static?void?main(String[]?args)??{
????????System.out.println("主線程ID:"+Thread.currentThread().getId());
????????MyRunnable?runnable?=?new?MyRunnable();
????????Thread?thread?=?new?Thread(runnable);
????????thread.start();
????}
}
?
?
class?MyRunnable?implements?Runnable{
?????
????public?MyRunnable()?{
?????????
????}
?????
????@Override
????public?void?run()?{
????????System.out.println("子線程ID:"+Thread.currentThread().getId());
????}
}

The Chinese meaning of Runnable is "task". As the name suggests, by implementing the Runnable interface, we define a subtask and then hand over the subtask to Thread for execution. . Note that this method must use Runnable as a parameter of the Thread class, and then use Thread's start method to create a new thread to perform the subtask. If you call Runnable's run method, no new thread will be created. This ordinary method call makes no difference.

In fact, if you look at the implementation source code of the Thread class, you will find that the Thread class implements the Runnable interface.

In Java, these two methods can be used to create threads to perform subtasks. Which method to choose depends on your own needs. Directly inheriting the Thread class may look simpler than implementing the Runnable interface, but since Java only allows single inheritance, if a custom class needs to inherit other classes, it can only choose to implement the Runnable interface.

3. Use Callable and Future to create threads

Unlike the Runnable interface, the Callable interface provides a call() method as a thread execution body, the call() method is more powerful than the run() method.

The steps to create and start a thread with a return value are as follows:

  1. Create an implementation class of the Callable interface, implement the call() method, and then create an instance of the implementation class (from 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 Implemented the Runnable interface)
  4. Call the get() method of the FutureTask object to obtain the return value after the execution of the child thread ends

The following is an example:

public?class?Main?{

  public?static?void?main(String[]?args){

   MyThread3?th=new?MyThread3();

   //使用Lambda表達式創(chuàng)建Callable對象

  ???//使用FutureTask類來包裝Callable對象

   FutureTask<Integer>?future=new?FutureTask<Integer>(

    (Callable<Integer>)()->{

      return?5;

    }

  ??);

   new?Thread(task,"有返回值的線程").start();//實質上還是以Callable對象來創(chuàng)建并啟動線程

  ??try{

    System.out.println("子線程的返回值:"+future.get());//get()方法會阻塞,直到子線程執(zhí)行結束才返回

?  ?}catch(Exception?e){

    ex.printStackTrace();

   }

  }

}

Comparison of three ways to create threads:

The methods of implementing Runnable and Callable interfaces are basically the same, but the latter has a return value when executing the call() method. The run() method of the thread execution body has no 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. Threads only implement Runnable Or implement the Callable interface, and you can also inherit other classes.

2. In this way, multiple threads can share a target object, which is very suitable for situations where multiple threads process the same resource.

3. However, programming is slightly complicated. If you need to access the current thread, you must call the Thread.currentThread() method.

4. A thread class that inherits the Thread class cannot inherit from other parent classes (determined by Java single inheritance).

PS: It is generally recommended to create multi-threads by implementing interfaces

This article comes from the Java Introduction column, welcome to learn!

The above is the detailed content of 3 ways to create threads in Java and their differences. 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.

Understanding the Java Virtual Machine (JVM) Internals Understanding the Java Virtual Machine (JVM) Internals Aug 01, 2025 am 06:31 AM

TheJVMenablesJava’s"writeonce,runanywhere"capabilitybyexecutingbytecodethroughfourmaincomponents:1.TheClassLoaderSubsystemloads,links,andinitializes.classfilesusingbootstrap,extension,andapplicationclassloaders,ensuringsecureandlazyclassloa

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,

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

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

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.

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

See all articles