search
HomeJavajavaTutorialHow to make threads execute in the order specified by themselves in 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);

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();

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){}
        }
    }
}

(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){}
        }
    }
}

(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();
    }
}

(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);

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

调用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
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
Is Java Platform Independent if then how?Is Java Platform Independent if then how?May 09, 2025 am 12:11 AM

Java is platform-independent because of its "write once, run everywhere" design philosophy, which relies on Java virtual machines (JVMs) and bytecode. 1) Java code is compiled into bytecode, interpreted by the JVM or compiled on the fly locally. 2) Pay attention to library dependencies, performance differences and environment configuration. 3) Using standard libraries, cross-platform testing and version management is the best practice to ensure platform independence.

The Truth About Java's Platform Independence: Is It Really That Simple?The Truth About Java's Platform Independence: Is It Really That Simple?May 09, 2025 am 12:10 AM

Java'splatformindependenceisnotsimple;itinvolvescomplexities.1)JVMcompatibilitymustbeensuredacrossplatforms.2)Nativelibrariesandsystemcallsneedcarefulhandling.3)Dependenciesandlibrariesrequirecross-platformcompatibility.4)Performanceoptimizationacros

Java Platform Independence: Advantages for web applicationsJava Platform Independence: Advantages for web applicationsMay 09, 2025 am 12:08 AM

Java'splatformindependencebenefitswebapplicationsbyallowingcodetorunonanysystemwithaJVM,simplifyingdeploymentandscaling.Itenables:1)easydeploymentacrossdifferentservers,2)seamlessscalingacrosscloudplatforms,and3)consistentdevelopmenttodeploymentproce

JVM Explained: A Comprehensive Guide to the Java Virtual MachineJVM Explained: A Comprehensive Guide to the Java Virtual MachineMay 09, 2025 am 12:04 AM

TheJVMistheruntimeenvironmentforexecutingJavabytecode,crucialforJava's"writeonce,runanywhere"capability.Itmanagesmemory,executesthreads,andensuressecurity,makingitessentialforJavadeveloperstounderstandforefficientandrobustapplicationdevelop

Key Features of Java: Why It Remains a Top Programming LanguageKey Features of Java: Why It Remains a Top Programming LanguageMay 09, 2025 am 12:04 AM

Javaremainsatopchoicefordevelopersduetoitsplatformindependence,object-orienteddesign,strongtyping,automaticmemorymanagement,andcomprehensivestandardlibrary.ThesefeaturesmakeJavaversatileandpowerful,suitableforawiderangeofapplications,despitesomechall

Java Platform Independence: What does it mean for developers?Java Platform Independence: What does it mean for developers?May 08, 2025 am 12:27 AM

Java'splatformindependencemeansdeveloperscanwritecodeonceandrunitonanydevicewithoutrecompiling.ThisisachievedthroughtheJavaVirtualMachine(JVM),whichtranslatesbytecodeintomachine-specificinstructions,allowinguniversalcompatibilityacrossplatforms.Howev

How to set up JVM for first usage?How to set up JVM for first usage?May 08, 2025 am 12:21 AM

To set up the JVM, you need to follow the following steps: 1) Download and install the JDK, 2) Set environment variables, 3) Verify the installation, 4) Set the IDE, 5) Test the runner program. Setting up a JVM is not just about making it work, it also involves optimizing memory allocation, garbage collection, performance tuning, and error handling to ensure optimal operation.

How can I check Java platform independence for my product?How can I check Java platform independence for my product?May 08, 2025 am 12:12 AM

ToensureJavaplatformindependence,followthesesteps:1)CompileandrunyourapplicationonmultipleplatformsusingdifferentOSandJVMversions.2)UtilizeCI/CDpipelineslikeJenkinsorGitHubActionsforautomatedcross-platformtesting.3)Usecross-platformtestingframeworkss

See all articles

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

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.