Controls common functions of threads and controls common functions of threads.
Thread interrupted: Thread.Sleep () and Thread.Yield ()
Call the Thread in the Thread body.During sleep (), you need to input parameters in parentheses: milliseconds. Once the thread executes this rule, it enters the sleep state, no longer runs the program, and the cpu execution time is allowed. After the sleep time, the thread does not immediately enter the running state, but enters the ready state and other threads seize the cpu execution time.
// Define the class RunnableImp implements Runnable used to implement the Runnable interface {// unique method for re-writing Runnable runpublic void run () {for (int I = 0; I <10; I ++) {System. out. println ("Runnable -->" + I); if (I = 5) {try {Thread. sleep (3000); // sleep for 3000 milliseconds} catch (Exception e) {System. out. println (e );}}}}}
Class Test {public static void main (String args []) {// generate RunnableImp object RunnableImp ri = new RunnableImp (); // input ri, generate the Thread object Thread t = new Thread (ri); // call the Thread's start method t. start ();}}
When the value of I is 5, the program will continue running after 3000 milliseconds.
Call the Thread in the Thread body.During yield (), when this line of code is run, the current thread automatically gives in and does not occupy the cpu execution time to enter the ready state. It can seize the cpu execution time again with other threads, other threads cannot be executed.
Set the thread priority: getPriority () and setPriority ()
Class Test {public static void main (String args []) {RunnableImp ri = new RunnableImp (); Thread t = new Thread (ri ); // obtain the default priority of thread t: System. out. println (t. getPriority (); // sets the maximum thread priority t. setPriority (Thread. MAX_PRIORITY); System. out. println (t. getPriority (); // sets the minimum thread priority t. setPriority (Thread. MIN_PRIORITY); System. out. println (t. getPriority (); t. start ();}}
The Thread has a maximum priority of 10 and a minimum priority of 1. You can set the Thread priority through static constants provided by the Thread. The higher the priority, the higher the thread execution probability.