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

王林
王林forward
2023-05-04 18:10:071475browse

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:yisu.com. If there is any infringement, please contact admin@php.cn delete