thread priority

await 2021-09-15 09:58:41

Thread priority is used by thread scheduling to determine when each thread is allowed to run . Theoretically , Higher priority threads get more... Than lower priority threads CPU Time . actually , Thread gets CPU Time is usually determined by a number of factors including priority ( for example , How can an operating system that implements multitasking make more effective use of CPU Time ).

A high priority thread naturally takes precedence over a low priority thread . for instance , When a low priority thread is running , And a high priority thread is restored ( For example, from sleeping or waiting I/O in ), It will preempt the resources used by low priority threads CPU.

Theoretically , Equal priority threads have equal rights to use CPU. But you have to be careful . remember ,Java It is designed to work in many environments . Multitasking in some environments is fundamentally different from other environments . To be on the safe side , Equal priority threads are occasionally controlled . This ensures that all threads have a chance to run under a non priority operating system . actually , In a non priority environment , Most threads still have a chance to run , Because many threads inevitably encounter blocking , For example, wait for input and output . In this case , Blocked thread suspended , Other threads run .

But if you want multithreading to run smoothly , It's best not to use this method . Again , Some types of tasks account for CPU Of . For these domination CPU Type of thread , Sometimes you want to be able to dominate them , So that other threads can run .

Set the priority of the thread , use setPriority() Method , This method is also Tread Members of . Its usual form is :

final void setPriority(int level)

this in , level finger Sets the new priority setting for the called thread .Level The value of must be at MIN_PRIORITY To MAX_PRIORITY Within the scope of . Usually , Their values are 1 and 10. To return a thread to the default priority , Appoint NORM_PRIORITY, Usually the value is 5. These priorities are Thread Are defined as final Type variable .

You can call Thread Of getPriority() Method to get the current priority setting . The method is as follows :

final int getPriority( )

When scheduling is involved ,Java The execution of can have essentially different behaviors .Windows 95/98/NT/2000 Your work is more or less what you want . But other versions may work completely differently . Most conflicts occur when you use threads with priority behavior , Instead of working together to free up CPU Time . The safest way is to get the priority of predictability ,Java The way to get cross platform thread behavior is to automatically give up on CPU The control of .

The following example illustrates two threads with different priorities , Run on a priority platform , This is different from running on a platform without priority . A thread passes Thread.NORM_PRIORITY Set the level two levels higher than the normal priority , The other thread sets two levels lower priority than the normal level . Two threads are started and allowed to run 10 second . Each thread executes a loop , Record the number of repetitions .10 Seconds later , The main thread terminated two threads . The number of cycles per thread is displayed . // Demonstrate thread priorities. class clicker implements Runnable {

 int click = 0;
Thread t;
private volatile boolean running = true;
public clicker(int p) {
t = new Thread(this);
t.setPriority(p);
}
public void run() {
while (running) {
click++;
}
}
public void stop() {
running = false;
}
public void start() {
t.start();
}

}

class HiLoPri {

public static void main(String args[]) {
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
clicker hi = new clicker(Thread.NORM_PRIORITY + 2);
clicker lo = new clicker(Thread.NORM_PRIORITY - 2);
lo.start();
hi.start();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
lo.stop();
hi.stop();
// Wait for child threads to terminate.
try {
hi.t.join();
lo.t.join();
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println("Low-priority thread: " + lo.click);
System.out.println("High-priority thread: " + hi.click);
}

}

The program in Windows 98 Output running under , Indicates that the thread does switch up and down , Not even submit to CPU, It is not blocked by input and output . High priority threads get about 90% Of CPU Time . Low-priority thread: 4408112 High-priority thread: 589626904

Of course , The exact output of the program depends on your CPU Speed and number of other tasks running . When the same program runs on a non priority system , There will be different results .

There is another noteworthy aspect of the above procedure . Be careful running Keywords before volatile. Even though volatile It will be discussed in detail in the next chapter , Used here to ensure running The value of is verified each time in the following loop . while (running) { click++; }

If not volatile,Java You can freely optimize the loop :running The value of exists CPU In a register of , It is not necessary to recheck every time .volatile The use of prevents the optimization , inform Java running You can change , change The method is not shown in direct code . Thread priority is used by thread scheduling to determine when each thread is allowed to run . Theoretically , Higher priority threads get more... Than lower priority threads CPU Time . actually , Thread gets CPU Time is usually determined by a number of factors including priority ( for example , How can an operating system that implements multitasking make more effective use of CPU Time ).

A high priority thread naturally takes precedence over a low priority thread . for instance , When a low priority thread is running , And a high priority thread is restored ( For example, from sleeping or waiting I/O in ), It will preempt the resources used by low priority threads CPU.

Theoretically , Equal priority threads have equal rights to use CPU. But you have to be careful . remember ,Java It is designed to work in many environments . Multitasking in some environments is fundamentally different from other environments . To be on the safe side , Equal priority threads are occasionally controlled . This ensures that all threads have a chance to run under a non priority operating system . actually , In a non priority environment , Most threads still have a chance to run , Because many threads inevitably encounter blocking , For example, wait for input and output . In this case , Blocked thread suspended , Other threads run .

But if you want multithreading to run smoothly , It's best not to use this method . Again , Some types of tasks account for CPU Of . For these domination CPU Type of thread , Sometimes you want to be able to dominate them , So that other threads can run .

Set the priority of the thread , use setPriority() Method , This method is also Tread Members of . Its usual form is :

final void setPriority(int level)

this in , level finger Sets the new priority setting for the called thread .Level The value of must be at MIN_PRIORITY To MAX_PRIORITY Within the scope of . Usually , Their values are 1 and 10. To return a thread to the default priority , Appoint NORM_PRIORITY, Usually the value is 5. These priorities are Thread Are defined as final Type variable .

You can call Thread Of getPriority() Method to get the current priority setting . The method is as follows :

final int getPriority( )

When scheduling is involved ,Java The execution of can have essentially different behaviors .Windows 95/98/NT/2000 Your work is more or less what you want . But other versions may work completely differently . Most conflicts occur when you use threads with priority behavior , Instead of working together to free up CPU Time . The safest way is to get the priority of predictability ,Java The way to get cross platform thread behavior is to automatically give up on CPU The control of .

The following example illustrates two threads with different priorities , Run on a priority platform , This is different from running on a platform without priority . A thread passes Thread.NORM_PRIORITY Set the level two levels higher than the normal priority , The other thread sets two levels lower priority than the normal level . Two threads are started and allowed to run 10 second . Each thread executes a loop , Record the number of repetitions .10 Seconds later , The main thread terminated two threads . The number of cycles per thread is displayed . // Demonstrate thread priorities. class clicker implements Runnable {

 int click = 0;
Thread t;
private volatile boolean running = true;
public clicker(int p) {
t = new Thread(this);
t.setPriority(p);
}
public void run() {
while (running) {
click++;
}
}
public void stop() {
running = false;
}
public void start() {
t.start();
}

}

class HiLoPri {

public static void main(String args[]) {
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
clicker hi = new clicker(Thread.NORM_PRIORITY + 2);
clicker lo = new clicker(Thread.NORM_PRIORITY - 2);
lo.start();
hi.start();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
lo.stop();
hi.stop();
// Wait for child threads to terminate.
try {
hi.t.join();
lo.t.join();
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println("Low-priority thread: " + lo.click);
System.out.println("High-priority thread: " + hi.click);
}

}

The program in Windows 98 Output running under , Indicates that the thread does switch up and down , Not even submit to CPU, It is not blocked by input and output . High priority threads get about 90% Of CPU Time . Low-priority thread: 4408112 High-priority thread: 589626904

Of course , The exact output of the program depends on your CPU Speed and number of other tasks running . When the same program runs on a non priority system , There will be different results .

There is another noteworthy aspect of the above procedure . Be careful running Keywords before volatile. Even though volatile It will be discussed in detail in the next chapter , Used here to ensure running The value of is verified each time in the following loop . while (running) { click++; }

If not volatile,Java You can freely optimize the loop :running The value of exists CPU In a register of , It is not necessary to recheck every time .volatile The use of prevents the optimization , inform Java running You can change , change The method is not shown in direct code .

This article altogether 2050 Number of words , Average reading time ≈ 6 minute

Participation of this paper Tencent cloud media sharing plan , You are welcome to join us , share .

Please bring the original link to reprint ,thank
Similar articles

2021-09-15