Java Thread Programming 1.6-Thread Prioritization

Source: Internet
Author: User
System Thread Priorities-JDK 1.2
Priority Thread Name
5 Main
8 Finalizer
10 Reference Handler
5 Signal dispatcher
5 AWT-Windows
6 AWT-EventQueue-0
5 SunToolkit. PostEventQueue-0
4 Screen Updater
A notable change in JDK 1.2 is that the priority of the Finalizer thread was increased from 1 to 8 to help ensure that the garbage collector gets more of a chance to run and free up memory. in Jdk1.2, the priority of the Finalizer thread increases from 1 to 8, ensuring that the garbage collector can recycle resources in time to release the memory When assigning priorities to your threads, you shoshould consider the relative priorities of the system threads to be sure your threads don't overwhelm their operations. by default, when a new Thread is constructed, it runs at the same priority as the thread that constructed it. most new threads are constructed directly or indirectly by the main thread and will therefore run at a priority of 5. this works well under extends scenarios, but there are times when you will want to raise or lower a thread's priority. the subthread has the same priority as the parent thread. Most threads are created from the main thread, so the priority is 5 There are three public static final int member variables of Thread that indicate the range of priority values that can be passed to setPriority (). Thread. MAX_PRIORITY Thread. MIN_PRIORITY Thread. NORM_PRIORITY  The Thread class has three static priority variables: Thread. MAX_PRIORITY. The highest priority, usually 10Thread. MIN_PRIORITY. The lowest priority is 1Thread. NORM_PRIORITY. Generally, the priority is 5.   GetPriority ()  The getPriority () method of Thread returns an int representing the current priority of the thread. generally, a thread's priority does not change over its lifetime, but it can. getPriority () returns the current priority of the thread. Generally, the priority of the thread remains unchanged in its lifecycle, but can be changed. SetPriority ()  The setpriority () method of thread takes an int as a parameter indicating the new priority for the thread. the setpriority () method can be invoked either before the thread is started or once it is running. some VMS might allow you to change the priority of the system threads, but this is not recommended-even if it is permitted. setpriority () sets the new thread priority. It can be called before the thread starts or during thread running. Some virtual machines allow changing the priority of the system thread, but we do not recommend this Can throw a securityexception if the calling thread is not permitted to make the priority change. this will happen only if there is a securitymanager installed and it rejects the change request. by default, applications do not have a securitymanager. if the thread priority cannot be changed, a securityexception is thrown when the setpriority () method is called. When securitymanager is installed, an illegalargumentexception will be thro. Wn if the specified priority is greater than thread. max_priority or less than thread. min_priority.allowed for the thread group. for example, in this code fragment thread t = //... threadgroup Tg = T. getthreadgroup (); int groupmax = Tg. getmaxpriority (); the maximum value for the thread priority of thread t is groupmax. usually, this is the same as thread. max_priority. when groupmax is less than threa D. max_priority, callto setpriority () still work, but will silently reduce the value passed to groupmax. if groupmax is 6 and setpriority (9) is called, the code will run as if setpriority (6) was called instead. see Chapter 10, "thread groups," for more on threadgroup. if you set the thread priority in the thread group's thread. max_priority, and thread. in addition to min_priority, The illegalargumentexception exception is thrown. Maximum priority allowed by the thread group and thread. maxpriority may be inconsistent. If the maximum priority of the thread group is 6 and the thread priority is set to 9, the code execution result is the same as setpriority (6.     Thread States  
State Blocked Interrupted Discription
Running     Current running on the processor
Ready to run     Waiting for the processor
Sleeping √ √ Will move to "ready to run" stateafter a certain amount of time has sed or after being interrupted
Waiting √ √ Will move to "ready to run" stateafter being notice, after timeout or after being interrupted
Blocked on I/O √   Will move to "ready to run" after I/OCondition changes (for example, a byte of date is read)
Blocked on sync √   Will move to "ready to run" when lock is acquired (passes synchronized statement)
 Threads can be BlockedIn one of four states. when a thread executes Thread. sleep (), it blocks until the specified number of milliseconds passes or until it is interrupted by another thread. when a thread encounters a wait () statement (see Chapter 8, "Inter-thread Communication," for more on the wait/notify mechanic), it blocks until it is notified, interrupted, or the specified number of milliseconds elapses (if a timeout was specified ). there are always ways a thread can block waiting on different I/O methods. one common way is the read () method of InputStream. this method blocks until a byte of data is read from the stream. it can block indefinitely, and no timeout can be specified. A thread can also block waiting to acquire exclusive access to an object's lock. the synchronized statement and synchronized method modifier (see Chapter 7, "Concurrent Access to Objects and Variables," for more on synchronization) are used to control concurrent access by more than one thread to a section of code. A thread will block on synchronized until it gets the specified lock. it can block indefinitely, and no timeout can be specified. there are four ways of Thread blocking: 1. Call Thread. sleep (), time completed, changed status when interrupted by other threads 2. When wait/notify occurs, the thread is interrupted by other threads when it is notified, or change the status at the end of a specific time. 3. I/O blocking. 4. Lock blocking. When the thread gets the lock, it changes the status Notice that NotAll blocked states are interruptible. when a thread is blocked waiting to read a byte of data from an InputStream, it will not respond to interrupts (see Chapter 15, "Breaking Out of a Blocked I/O State, "for some techniques for dealing with this ). when a thread is blocked waiting to get the lock required by a synchronized statement, it also will not respond to interrupt requests (see Chapter 17, "BooleanLock Utility, "for a technique that deals with long waits for locks ). not all blocking states can be interrupted. I/O blocking and lock blocking cannot be interrupted. Thread. yield ()  To help ensure that other threads in the VM get a turn to run on the processor, a thread can voluntarily give up its turn early. if a thread invokes the static method Thread. yield (), the thread schedther will swap it off the processor and allow another thread to run. it is likely (but not guaranteed) that only threads having a priority EqualOr GreaterThe one that yielded control will be considered by the thread scheduler. thread. yield (): The thread voluntarily gives control of the CPU. A thread implicitly yields the processor when it goes to sleep or otherwise blocks. the thread. yield () method allows a thread to specify other times that are convenient for it to pause to allow other threads access to the processor. if you have a thread that frequently blocks on its own, there is no Need to make thread. yield () CILS. but, if you have a thread that is creating Ming a long non-blocking calculation, an occasional call to thread. yield () can help split up the processor resources among the other threads. be careful not to overuse thread. yield () as some system overhead is incurred to perform a context switch between threads. as a rough guideline, try to avoid calling thread. yield () Mo Re than five times per second. When the thread is blocked (for four reasons), the thread implicitly implements its own yield. If the thread itself is often congested, there is no need to explicitly call yield. If the thread executes a large computing task that is not blocked for a long time, it can split the processor resources equally for other processes. Note: Do not call it frequently, because the system performs context switching during yield, which consumes system resources and time to avoid calling more than five yield requests within seconds. Instance: PriorityYield. java/** Created on 2005-7-8 ** Java Thread Programming-Paul Hyde * copyright? 1999 SAMs publishing * Jonathan Q. bo Study Notes **/package Org. tju. msnrl. jonathan. thread. chapter1;/*** @ author Jonathan Q. bo from tju msnrl ** E-mail: jonathan.q.bo@gmail.com * blog: blog.csdn.net/jonathan_q_bo * blog.yesky.net/jonathanundersun ** enjoy life with sun! **/Public class priorityyield {private volatile int counter; private thread innerthread; private volatile Boolean stoprequest; private Boolean yield; Public priorityyield (string name, int priority, Boolean yield) {This. yield = yield; this. counter = 0; this. stoprequest = false; runnable r = new runnable () {public void run () {try {runwork ();} catch (exception e) {system. out. println (E. getmessage ());} }; Innerthread = new thread (R, name); innerthread. setpriority (priority);}/** thread subject */Public void runwork () {thread. yield (); While (! This. stoprequest) {If (this. yield) {thread. yield () ;}counter ++; Double X = 0; For (INT I = 0; I <1000; I ++) // puts the thread in the active state, instead of sleep x = math. pI * I/math. e;}/** start thread */Public void startthread () {This. innerthread. start ();}/** end thread */Public void stopthread () {This. stoprequest = true;} public int getcounter () {return this. counter;}/** return thread priority and thread name */Public String getpriorityandname () {return "thread:" + innerthread. getname () + "/Priority:" + innerthread. getpriority ();} public static void runmain (Boolean yield) {/* define three threads */priorityyield [] pys = new priorityyield [3]; pys [0] = new priorityyield ("py0", 3, yield); pys [1] = new priorityyield ("py1", 6, yield ); pys [2] = new priorityyield ("py2", 6, yield); try {thread. sleep (1000);} catch (interruptedexception e) {}/* Start three threads */For (INT I = 0; I <pys. length; I ++) {pys [I]. startthread ();} Long starttime = system. currenttimemillis ();/* run the thread for a period of time */try {thread. sleep (10000);} catch (interruptedexception e) {}/* Stop the thread running */For (INT I = 0; I <pys. length; I ++) {pys [I]. stopthread ();} Long stoptime = system. currenttimemillis ();/* and other threads completely stop running */try {thread. sleep (1000);} catch (interruptedexception e) {}/* Get the total number of three threads */INT totalcounter = 0; For (INT I = 0; I <pys. length; I ++) {totalcounter + = pys [I]. getcounter ();}/* output statistical result */system. out. println ("totalcount =" + totalcounter + "count/MS =" + totalcounter/(stoptime-starttime); For (INT I = 0; I <pys. length; I ++) {system. out. println (pys [I]. getpriorityandname () + ", Count =" + pys [I]. counter + "," + pys [I]. counter * 100/totalcounter + "%") ;}} public static void main (string [] ARGs) {runnable r = new runnable () {public void run () {system. out. println ("Run Without yield"); runmain (false); // do not use yield system. out. println (); system. out. println ("Run with yield"); runmain (true); // use yield }}; thread t = new thread (R, "priorityyield"); T. setpriority (thread. max_priority-1); T. start () ;}} output result: run without yieldtotalcount = 454665 counter/MS = 45 thread: py0/Priority: 3, Count = 0, 0% thread: py1/Priority: 6, count = 235049, 51% thread: py2/Priority: 6, Count = 219616, 48% run with yieldtotalcount = 401611 counter/MS = 40 thread: py0/Priority: 3, Count = 0, 0% thread: py1/Priority: 6, Count = 200805, 49% thread: py2/Priority: 6, Count = 200806, 50% by calling yield, the comparison experiment clearly shows that 1. Higher priority gets more processor cycles 2. the threads with the same priority have the same running opportunity 3. Calling yield does not increase performance, instead, it reduces the total CPU cycle also note that without yielding, the count/MS was about 76 (line 3), and when yielding was done, it was cut down to about 25 (Line 10 ). this shows that the yielding caused a lot of context switches that brought with them some significant overhead. in this example, the excessive yielding wasted processor resources. frequent yield waste of processor Resources When assigning priorities to the threads in your application, use the higher priorities only for threads that block frequently (sleeping, waiting, I/O ). CPU-intensive calculations shoshould be done with a medium-to low-priority thread to ensure that the processor is not hogged. avoid setting a priority to Thread. MAX_PRIORITY unless the thread specified DS nearly all of its time blocked or is very short-liv Ed. for high priority threads that are frequently congested, ensure that the processor is not exclusive to low priority threads in intensive computing, and avoid setting the priority to Thread. MAX_PRIORITY, unless the Thread's life cycle is particularly short or is basically blocked throughout the life cycle Thread scheduling varies from VM to VM and from operating system to operating system. because of these differences, prioritization shocould only be used to try to improve responsiveness and efficiency, and shocould not be relied upon for program correctness. different virtual machines and different operating systems have different thread calling mechanisms. Because of these differences, the thread priority is only used to increase the response speed. And efficiency.

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.