Java know how much (61) thread Priority

Source: Internet
Author: User
Tags java throws

Thread priority is dispatched by the thread to determine when each thread is allowed to run. In theory, higher-priority threads get more CPU time than threads with lower priority. In fact, the CPU time that a thread obtains is usually determined by a number of factors, including priority (for example, how a multitasking operating system can utilize CPU time more efficiently).

A thread with a high priority is naturally preferable to a thread with a lower priority. For example, when a low-priority thread is running, and a high-priority thread is restored (for example, from a slumber or waiting for I/O), it will preempt the CPU used by the low-priority thread.

In theory, such priority threads have equal rights to use the CPU. But you have to be careful. Remember, Java is designed to work in many environments. Implementing multitasking in some environments is inherently different from other environments. For security reasons, such as priority threads are occasionally also under control. This ensures that all threads have an opportunity to run under a non-priority operating system. In fact, in a no-priority environment, most threads still have the opportunity to run because many threads inevitably encounter blocking, such as waiting for input and output. In this scenario, the blocked thread hangs and the other threads run.

But if you want multithreaded execution to be smooth, it's best not to use this approach. Similarly, some types of tasks are CPU-occupied. For these threads that dominate the CPU type, sometimes you want to be able to dictate them so that other threads can run.

Sets the priority of the thread, using the SetPriority () method, which is also a member of the tread. The usual form of it is:

1     Final void setpriority (int level)

Here, the level specifies the new priority setting for the called Thread. The level value must be within the range of min_priority to max_priority. Typically, their values are 1 and 10, respectively. To return a thread as the default priority, specify Norm_priority, which typically has a value of 5. These priorities are defined as final variables in thread.


You can get the current priority setting by calling the thread's GetPriority () method. The method is as follows:

1     Final int getpriority ()

When scheduling is involved, Java execution can have a fundamentally different behavior. Windows 95/98/nt/2000 work more or less as you wish. But the other versions may work completely differently. Most contradictions occur when you use a thread that has priority behavior instead of working together to free up CPU time. The safest approach is to get the preemptive priority, and the way in which Java obtains the cross-platform threading behavior is to automatically abandon the control of the CPU.


The following example illustrates two different priority threads, running on a platform with priority, which is different from a platform running on a non-priority level. One thread sets a level higher than the normal priority level two through thread.norm_priority, and the priority of the other is lower than the normal level of two. Two threads are started and allowed to run for 10 seconds. Each thread executes a loop, recording the number of repetitions. After 10 seconds, the main thread terminates two threads. The number of cycles per thread is displayed.

1 //demonstrate thread priorities.2 classClickerImplementsRunnable {3      intClick = 0;4 Thread t;5     Private volatile Booleanrunning =true;6      PublicClickerintp) {7t =NewThread ( This);8 t.setpriority (p);9     }Ten  One      Public voidrun () { A          while(running) { -click++; -         } the     } -  -      Public voidStop () { -running =false; +     } -  +      Public voidstart () { A T.start (); at     } - } -  - classHilopri { -      Public Static voidMain (String args[]) { - Thread.CurrentThread (). setpriority (thread.max_priority); inClicker hi =NewClicker (thread.norm_priority + 2); -Clicker lo =NewClicker (thread.norm_priority-2); to Lo.start (); + Hi.start (); -         Try { theThread.Sleep (10000); *}Catch(interruptedexception e) { $System.out.println ("Main thread interrupted."));Panax Notoginseng         } - lo.stop (); the hi.stop (); +         //Wait for the child threads to terminate. A         Try { the Hi.t.join (); + Lo.t.join (); -}Catch(interruptedexception e) { $SYSTEM.OUT.PRINTLN ("Interruptedexception caught"); $         } -  -System.out.println ("Low-priority Thread:" +Lo.click); theSystem.out.println ("High-priority Thread:" +Hi.click); -     }Wuyi}

The output of the program running under Windows 98 indicates that the thread is actually transitioning up or down, even without succumbing to the CPU or being blocked by the input output. High-priority threads get about 90% of the CPU time.

Low-priority thread:4408112High-priority thread:589626904

Of course, the exact output of the program depends on the speed of your CPU and the number of other tasks that are running. When the same program runs on a system with no priority, there will be different results.


The above procedure also has a notable place. Note the keyword volatile before running. Although volatile is discussed very carefully in the next chapter, it is used here to ensure that the value of running is validated every time in the following loop.

1  while (running) {2     click++; 3 }

If you don't use Volatile,java, you can optimize the loop freely: the value of running is in a register of the CPU,

Each repetition does not necessarily require a retest. The use of volatile prevents the optimization, informing Java running can change, change
The method is not displayed in direct code form.

Series Articles:

Java know how much (top)

Java know how much (interface) interface

Java knows how much (40) the difference between an interface and an abstract class

Java know how much (41) generic explanation

Java know how much (42) the range of generic wildcard characters and type parameters

Java know how much (43) Exception Handling Basics

Java know how much (44) exception type

Java know how much (45) uncaught exceptions

How much Java knows (the) use of try and catch

Java know how much (47) use of multiple catch statements

Java knows how much (in) the nesting of Try statements

Java know how much (a) throw: Exception throws

Java know how many () Java throws clauses

Java knows how many (or) finally

Java know how much (52) built-in exceptions

Java know how much (53) Use Java to create your own exception subclasses

Java know how much (54) assertion detailed

Java know how many (55) threads

Java know how much (56) threading ModelJava know how much (57) main threadJava know how much (58) thread Runnable interface and thread class explanationJava know how much (59) Create multithreadingJava know how much (isAlive) and join () use

Java know how much (61) thread Priority

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.