Home Java javaTutorial Summary of Java multi-threaded programming methods (with examples)

Summary of Java multi-threaded programming methods (with examples)

Sep 27, 2018 pm 02:38 PM
java multithreading

This article brings you a summary of Java multi-threading implementation methods (with examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. When to use multi-threaded programming

A task is executed in sequence under normal circumstances, but if there are multiple similar process blocks in the current task (such as for, while statements) , we can consider extracting these code blocks to run in parallel without blocking

2. Several ways to implement multi-threading

One is to inherit the Thread class and rewrite the run method, and the other is to inherit the Thread class and rewrite the run method. The first is to implement the Runnable interface and rewrite the run method

Starting multi-threads is often used to handle concurrent processes. At this time, for some business needs that do not require high real-time performance, we can also implement queues. Asynchronous implementation.

3. Example

Inherit Thread

/**
 * 
* @ClassName: ThreadByEx  
* @Description: TODO
* @author Mr.jqCheng
* @date 2018年9月26日  
* */public class ThreadByEx extends Thread{

    @Override    public void run() {        // TODO Auto-generated method stub
        System.out.println("我是继承线程");
    }

}
Copy after login

Implement Runnable

/**
 * 
* @ClassName: ThreadByRunnable  
* @Description: TODO
* @author Mr.jqCheng
* @date 2018年9月26日  
* */public class ThreadByRunnable implements Runnable{    /*public ThreadByRunnable() {
        this.run();
        // TODO Auto-generated constructor stub
    }*/

    public void run() {        // TODO Auto-generated method stub
        System.out.println("我是实现进程");
    }

}
Copy after login

Test:

/**
 * 
* @ClassName: Test  
* @Description: TODO
* @author Mr.jqCheng
* @date 2018年9月26日  
* */public class Test {    public static void main(String[] args) {        // 继承Thread启动的方法
        ThreadByEx t1 = new ThreadByEx();
        t1.start();// 启动线程        // 实现Runnable启动线程的方法
        ThreadByRunnable r = new ThreadByRunnable();
        Thread t2 = new Thread(r);
        t2.start();// 启动线程        //new ThreadByRunnable();    }

}
Copy after login

Running result:

I am an inherited thread
I am an implementation process

ok, the simple multi-thread implementation is completed. When start() is called, the process has entered the executable state and is waiting for system execution.

Several common methods of thread processing:

void interrupt(): Send an interrupt request to the thread, the interrupt status of the thread will be set to true, if the current thread is blocked by a sleep call , then an interruptedException will be thrown.

static boolean interrupted(): Test whether the current thread (the thread currently executing the command) is interrupted. Note that this is a static method. Calling this method will have a side effect, that is, it will reset the interrupt status of the current thread to false.

boolean isInterrupted(): Determine whether the thread has been interrupted. The call of this method will not have side effects, that is, it will not change the current interruption status of the thread.

static Thread currentThread(): Returns the Thread object representing the current execution thread.

Daemon process

Used to serve all threads under all other current processes that are not service processes

Just implement deamon.setDaemon(true), before the thread is started Enable

Example

package com.orange.util;
/**
 * 
 * @ClassName: Test
 * @Description: TODO
 * @author Mr.jqCheng
 * @date 2018年9月26日
 *
 */
public class Test {
    public static void main(String[] args) {
        Thread deamon2 = new Thread(new DaemonRunner2(), "otherRunner");
        deamon2.start();// 启动线程
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Thread deamon = new Thread(new DaemonRunner(), "DaemonRunner");
        // 设置为守护线程
        deamon.setDaemon(true);
        deamon.start();// 启动线程
    }
    static class DaemonRunner implements Runnable {
        public void run() {
            // TODO Auto-generated method stub
            try {
                Thread.sleep(300);
                Thread t = Thread.currentThread();
                System.out.println(t);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                System.out.println("进入守护线程,说明现在还有其他线程在执行");
            }
        }
    }
    static class DaemonRunner2 implements Runnable {
        public void run() {
            // TODO Auto-generated method stub
            try {
                Thread.sleep(1500);
                System.out.println("我是其他线程");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
Copy after login

Execution result:

Thread[DaemonRunner,5,main]
Enter the daemon thread, indicating that there are other threads executing
I am other threads

First, start other threads first, which takes 1500ms. At the same time, after the main thread takes 1000ms, it starts to enter the daemon thread. At this time, other threads are still running. When it comes to the daemon thread, it takes time 300ms, other threads are still executing, continue down, the daemon thread has completed execution

But if I change the daemon thread's 300ms to 500ms, what will happen?

There have been two situations, after all, at the critical value

1. I am another thread

2.Thread[DaemonRunner,5,main]
Enter the daemon thread , indicating that there are other threads executing now
I am another thread

The above is the detailed content of Summary of Java multi-threaded programming methods (with examples). 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

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.

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

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

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.

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

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.

See all articles