Table of Contents
What is a thread:
Home Java javaTutorial How to create multithreading in java? (detailed)

How to create multithreading in java? (detailed)

Sep 25, 2018 pm 03:32 PM
java multithreading

The content of this article is about how to create multi-threading in Java? (Details), it has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

What is a thread:

A thread is an entity in the process. It is a basic unit that is independently scheduled and dispatched by the system. The thread itself does not own system resources, only It is an indispensable resource during operation, but it can share all the resources owned by the process with other threads belonging to the same process.

On the surface, it is multi-threading, but it is actually a fast execution of the CPU in turns.

##Multi-threading (parallel and concurrency)

  1. Parallel: two tasks are performed at the same time, that is, while task A is executing, task B is also executing (multi-core required)

  2. Concurrency: Both tasks are requested to run, and the processor can only accept one task, so the two tasks are scheduled to be executed in turn. Since the time interval is very short, it makes people feel that both tasks are running

Multi-threading (the principle of running java program)

The java command will start the jvm, which is equivalent to starting An application (a process). The process will automatically start the "main thread", and the main thread will call the main method


Is starting the jvm single-threaded?

No, it is multi-threaded. At least the garbage collection thread and the main thread will be started


It can be verified through the following code that the main thread and the garbage collection thread are competing for resources from each other

public class TestThread {

    public static void main(String[] args) {
        //4.创建Thread的子类对象
        MyThread myThread = new MyThread();

        //5.启动线程,注意这里使用的是start而不是run方法
        myThread.start();

        for (int i = 0; i < 10000; i ++) {
            System.out.println("This is main thread");
        }
    }


}

//1.继承Thread
class MyThread extends  Thread{

    //2.重写run方法
    @Override
    public void run() {
        super.run();
        //3.线程方法中要执行的代码,可以根据自己的需求填写
        for(int i = 0 ; i < 10000 ; i ++ ) {
            System.out.println("This is MyThread thread ");
        }
    }
}
Copy after login

How to create multi-threads in java

(1) Inherit the Thread class and call the start method

Thread implements the Runnable interface

To implement multi-threading, you must become a subclass of thread and override the run method. Note that when starting a thread, it is not the run method but the start method that is called. If the run method is called, it is equivalent to a normal method and does not open the thread

public class Thread implements Runnable
Copy after login
public class TestThread {

    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        //注意这里使用的是start而不是run方法
        myThread.start();

        for (int i = 0; i < 10000; i ++) {
            System.out.println("This is main thread");
        }
    }
}
class MyThread extends  Thread{
    @Override
    public void run() {
        super.run();

        for(int i = 0 ; i < 10000 ; i ++ ) {
            System.out.println("This is MyThread thread ");
        }
    }
}
Copy after login

(2) Implement the runnable interface and rewrite the run method

There is only one method in Runnable, run(), The thread startup method exists in Thread,

then when we finally start the thread, we must start the thread through the subclass object of Thread

public class TestRunnable {

    public static void main(String[] args) {
        //4.创建Thread的子类对象
        Runnable myRunnable = new MyRunnable();

        //5.启动线程,创建Thread并把runnable的子类作为构造参数
        new Thread(myRunnable).start();

        for (int i = 0; i < 10000; i ++) {
            System.out.println("This is main thread");
        }
    }

}
//1.实现runnable接口
class MyRunnable implements Runnable {

    //2.重写run方法
    @Override
    public void run() {
        //3.线程方法中要执行的代码,可以根据自己的需求填写
        for(int i = 0 ; i < 10000 ; i ++ ) {
            System.out.println("This is MyRunnable thread ");
        }
    }
}
Copy after login

implement the Callable interface

To implement threads, in addition to inheriting thread and runnable, you can also implement the Callable interface. The Callable interface provides a call() method that can be used as a thread execution body, which has the same function as run(). But the call() method has more return values ​​than the run() method, and the call() method can declare the exception thrown. So how do we start the Callable thread? Because the Callable interface is not a sub-interface of the Runnable interface, the Callable object cannot be used as a construction parameter of Thread. Java provides another interface, the RunnableFuture interface, which implements Runnable, Future

  1. implementation

    Callableinterface

  2. Write the

    call method, which is equivalent to the run method in thread. The difference is that the call method allows a return value

  3. Pass the Callable implementation class object as a construction parameter to FutureTask to create a FutureTask object.

  4. Pass the FutureTask object as a construction parameter to Thread and start the thread

  5. public class CallableDemo {
    
        public static void main(String[] args) {
            //3.把Callable实现类对象作为构造参数传入FutureTask创建FutureTask对象。
            FutureTask<UUID> futureTask = new FutureTask<UUID>(new MyCallable());
            //4.把FutureTask对象作为构造参数传入Thread,并开启线程
            new Thread(futureTask).start();
            try {
                System.out.println(futureTask.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
    }
    
    //1. 实现**Callable**接口
    class MyCallable implements Callable<UUID> {
    
        //2.重写**call**方法,相当于thread中的run方法。不同的是call方法允许有返回值
        @Override
        public UUID call() throws Exception {
            //生成随机数
            return UUID.randomUUID();
        }
    }
    Copy after login
Inherit Thread to realize the difference between Runnable and Callable

From the source code implementation

Inherit Thread

The subclass rewrites the run() method in Thread and calls the start() method. The jvm will automatically call the subclass's run()

Implementing Runnable

new Thread(myRunnable) puts the reference of runnable in the constructor of Thread, and then passes it to the member variable target of thread. In the Thread run() method, it is determined that if the target is not empty, the run method of the subclass is called

    public void run() {
    if (this.target != null) {
        this.target.run();
    }
Copy after login

Implements the Callable interface

Implements the Callable interface and overrides the Call() method, and can Provides thread return values ​​and can also throw exceptions. Finally, it is passed to the member variable target of Thread through the implementation class FutureTask of Runnable's sub-interface RunnableFuture.

In terms of use and expansion

Inherit Thread

  1. Advantages: Directly call the start() method in thread, very simple

  2. Disadvantages: Java only supports single inheritance. If a subclass inherits thread, it cannot inherit other classes

Implement Runnable

  1. Advantages: java can implement many things

  2. Disadvantages: The code writing is complicated and start() cannot be called directly

implementation of Callable

  1. Advantages: Java can be implemented in multiple ways, can throw exceptions, and can have return values

  2. Disadvantages: Code writing is complicated

The above is the detailed content of How to create multithreading in java? (detailed). 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

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.

Undress AI Tool

Undress AI Tool

Undress images for free

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)

Java development optimization method for file reading multi-thread acceleration performance Java development optimization method for file reading multi-thread acceleration performance Jun 30, 2023 pm 10:54 PM

In Java development, file reading is a very common and important operation. As your business grows, so do the size and number of files. In order to increase the speed of file reading, we can use multi-threading to read files in parallel. This article will introduce how to optimize file reading multi-thread acceleration performance in Java development. First, before reading the file, we need to determine the size and quantity of the file. Depending on the size and number of files, we can set the number of threads reasonably. Excessive number of threads may result in wasted resources,

Detailed explanation of usage scenarios and functions of volatile keyword in Java Detailed explanation of usage scenarios and functions of volatile keyword in Java Jan 30, 2024 am 10:01 AM

Detailed explanation of the role and application scenarios of the volatile keyword in Java 1. The role of the volatile keyword In Java, the volatile keyword is used to identify a variable that is visible between multiple threads, that is, to ensure visibility. Specifically, when a variable is declared volatile, any modifications to the variable are immediately known to other threads. 2. Application scenarios of the volatile keyword The status flag volatile keyword is suitable for some status flag scenarios, such as a

Explore the working principles and characteristics of java multithreading Explore the working principles and characteristics of java multithreading Feb 21, 2024 pm 03:39 PM

Explore the working principles and characteristics of Java multithreading Introduction: In modern computer systems, multithreading has become a common method of concurrent processing. As a powerful programming language, Java provides a rich multi-threading mechanism, allowing programmers to better utilize the computer's multi-core processor and improve program running efficiency. This article will explore the working principles and characteristics of Java multithreading and illustrate it with specific code examples. 1. The basic concept of multi-threading Multi-threading refers to executing multiple threads at the same time in a program, and each thread processes different

Exception handling in Java multi-threaded environment Exception handling in Java multi-threaded environment May 01, 2024 pm 06:45 PM

Key points of exception handling in a multi-threaded environment: Catching exceptions: Each thread uses a try-catch block to catch exceptions. Handle exceptions: print error information or perform error handling logic in the catch block. Terminate the thread: When recovery is impossible, call Thread.stop() to terminate the thread. UncaughtExceptionHandler: To handle uncaught exceptions, you need to implement this interface and assign it to the thread. Practical case: exception handling in the thread pool, using UncaughtExceptionHandler to handle uncaught exceptions.

Java Multithreading Performance Optimization Guide Java Multithreading Performance Optimization Guide Apr 11, 2024 am 11:36 AM

The Java Multithreading Performance Optimization Guide provides five key optimization points: Reduce thread creation and destruction overhead Avoid inappropriate lock contention Use non-blocking data structures Leverage Happens-Before relationships Consider lock-free parallel algorithms

Detailed explanation of Java multi-threaded concurrency lock Detailed explanation of Java multi-threaded concurrency lock Apr 11, 2024 pm 04:21 PM

The Java concurrency lock mechanism ensures that shared resources are accessed by only one thread in a multi-threaded environment. Its types include pessimistic locking (acquire the lock and then access) and optimistic locking (check for conflicts after accessing). Java provides built-in concurrency lock classes such as ReentrantLock (mutex lock), Semaphore (semaphore) and ReadWriteLock (read-write lock). Using these locks can ensure thread-safe access to shared resources, such as ensuring that when multiple threads access the shared variable counter at the same time, only one thread updates its value.

Multi-thread safety issues in Java - solutions to java.lang.ThreadDeath Multi-thread safety issues in Java - solutions to java.lang.ThreadDeath Jun 25, 2023 am 11:22 AM

Java is a programming language widely used in modern software development, and its multi-threaded programming capabilities are also one of its greatest advantages. However, due to the concurrent access problems caused by multi-threading, multi-thread safety issues often occur in Java. Among them, java.lang.ThreadDeath is a typical multi-thread security issue. This article will introduce the causes and solutions of java.lang.ThreadDeath. 1. Reasons for java.lang.ThreadDeath

Java multi-thread debugging technology revealed Java multi-thread debugging technology revealed Apr 12, 2024 am 08:15 AM

Multi-threaded debugging technology answers: 1. Challenges in multi-threaded code debugging: The interaction between threads leads to complex and difficult-to-track behavior. 2. Java multi-thread debugging technology: line-by-line debugging thread dump (jstack) monitor entry and exit events thread local variables 3. Practical case: use thread dump to find deadlock, use monitor events to determine the cause of deadlock. 4. Conclusion: The multi-thread debugging technology provided by Java can effectively solve problems related to thread safety, deadlock and contention.

See all articles