Table of Contents
How to make threads execute in the order they specify
Understanding Join
Using Executors thread pool
Thread priority and execution order
Priority Overview
Using priorities
Home Java javaTutorial How to make threads execute in the order specified by themselves in Java

How to make threads execute in the order specified by themselves in Java

May 04, 2023 pm 06:10 PM
java

How to make threads execute in the order they specify

In daily multi-thread development, we may sometimes want each thread to run in the order we specify, instead of letting the CPU schedule randomly. , which may cause unnecessary trouble in our daily development work.

Now that there is this requirement, the title of this article is introduced to let the threads run in the order specified by themselves.

Interested students can guess the possible results of the following code:

How to make threads execute in the order specified by themselves in Java

According to the normal understanding, the execution of the above code The sequence should be: t1 → t2 → t3, but the actual effect is not ideal.

The picture below shows the running effect:

How to make threads execute in the order specified by themselves in Java

Understanding Join

join may not be easy for some students If you are unfamiliar with it, I will not introduce what Join is in detail here. Students who have questions can baidu and google it.

Here I will directly introduce how to use join to achieve the effect we want to see!

How to make threads execute in the order specified by themselves in Java

Here we mainly use the blocking effect of Join to achieve our purpose. Looking at the running results in the above figure, we can know that the program has been executed in the order we specified and obtained the results we wanted.

In fact, we can think deeply about why join can achieve the effect we want? Next, let’s take a look at the source code:

After entering the join source code, the first thing you see is a join method that passes in 0 parameters. Here, choose to continue entering.

How to make threads execute in the order specified by themselves in Java

First of all, you can see that the join method is thread-safe. Secondly, you can see it together with the above picture. When the incoming parameter is 0, a wait(0) will be hit. Method, experienced students should be able to understand it directly, here it means waiting.

But it should be noted that the waiting here is definitely not waiting for the caller, but the blocked main thread. t1, t2, and t3 are just sub-threads. When the sub-threads finish running, the main thread ends waiting.

This demonstrates how join works, and also proves that join can allow us to achieve the results we want in the program.

How to make threads execute in the order specified by themselves in Java

In addition to join helping us control the order of threads in the program, there are other ways. For example, let's try using the thread pool.

Using Executors thread pool

Executors is a thread pool operation class under the java.util.concurrent package in the JDK, which can conveniently provide us with thread pool operations.

Here we use the newSingleThreadExecutor() method in Executors to create a single-threaded thread pool.

How to make threads execute in the order specified by themselves in Java

As can be seen from the above figure, using the newSingleThreadExecutor() method can still achieve the results we expect. In fact, the principle is very simple. Inside the method is a FIFO-based queue, and That is to say, when we add t1, t2, and t3 to the queue in sequence, only the thread t1 is actually in the ready state, and t2 and t3 will be added to the queue. When t1 is completed, execution in the queue will continue. of other threads.

Thread priority and execution order

When learning operators, readers know that there is a priority between each operator. Understanding the priority of operators is very good for program development. effect. The same is true for threads. Each thread has a priority. The Java virtual machine determines the execution order of threads based on the priority of the thread, so that multiple threads can reasonably share CPU resources without conflict.

Priority Overview

In the Java language, the priority range of a thread is 1~10, and the value must be between 1~10, otherwise an exception will occur; the default value of priority is 5. Threads with higher priority will be executed first, and when execution is completed, it will be the turn of threads with lower priority to execute. If the priorities are the same, they will be executed in turn.

You can use the setPriority() method in the Thread class to set the priority of the thread. The syntax is as follows:

public final void setPriority(int newPriority);
Copy after login

If you want to get the priority of the current thread, you can call the getPriority() method directly. The syntax is as follows:

public final int getPriority();
Copy after login

Using priorities

After briefly understanding priorities, let’s use a simple example to demonstrate how to use priorities.

Example 1

Use the Thread class and Runnable interface to create threads respectively, and assign priorities to them.

public class FirstThreadInput extends Thread
{
    public void run()
    {
        System.out.println("调用FirstThreadInput类的run()重写方法");    //输出字符串
        for(int i=0;i<5;i++)
        {
            System.out.println("FirstThreadInput线程中i="+i);    //输出信息
            try
            {
                Thread.sleep((int) Math.random()*100);    //线程休眠
            }
            catch(Exception e){}
        }
    }
}
Copy after login

(2) Create a SecondThreadInput class that implements the Runnable interface and implements the run() method. code show as below:

public class SecondThreadInput implements Runnable
{
    public void run()
    {
        System.out.println("调用SecondThreadInput类的run()重写方法");    //输出字符串
        for(int i=0;i<5;i++)
        {
            System.out.println("SecondThreadInput线程中i="+i);    //输出信息
            try
            {
                Thread.sleep((int) Math.random()*100);    //线程休眠
            }
            catch(Exception e){}
        }
    }
}
Copy after login

(3) 创建 TestThreadInput 测试类,分别使用 Thread 类的子类和 Runnable 接口的对象创建线程,然后调用 setPriority() 方法将这两个线程的优先级设置为 4,最后启动线程。代码如下:

public class TestThreadInput
{
    public static void main(String[] args)
    {
        FirstThreadInput fti=new FirstThreadInput();
        Thread sti=new Thread(new SecondThreadInput());
        fti.setPriority(4);
        sti.setPriority(4);
        fti.start();
        sti.start();
    }
}
Copy after login

(4) 运行上述代码,运行结果如下所示。

调用FirstThreadInput类的run()重写方法
调用SecondThreadInput类的run()重写方法
FirstThreadInput线程中i=0
SecondThreadInput线程中i=0
FirstThreadInput线程中i=1
FirstThreadInput线程中i=2
SecondThreadInput线程中i=1
FirstThreadInput线程中i=3
SecondThreadInput线程中i=2
FirstThreadInput线程中i=4
SecondThreadInput线程中i=3
SecondThreadInput线程中i=4

由于该例子将两个线程的优先级都设置为 4,因此它们交互占用 CPU ,宏观上处于并行运行状态。

重新更改 ThreadInput 类的代码、设置优先级。代码如下:

fti.setPriority(1);
sti.setPriority(10);
Copy after login

重新运行上述代码,如下所示。

调用FirstThreadInput类的run()重写方法
调用SecondThreadInput类的run()重写方法
FirstThreadInput线程中i=0
SecondThreadInput线程中i=0
SecondThreadInput线程中i=1
SecondThreadInput线程中i=2
SecondThreadInput线程中i=3
SecondThreadInput线程中i=4
FirstThreadInput线程中i=1
FirstThreadInput线程中i=2
FirstThreadInput线程中i=3
FirstThreadInput线程中i=4

The above is the detailed content of How to make threads execute in the order specified by themselves 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

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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1248
24
Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

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

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

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

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

See all articles