Java threads (2)
1. The second method for implementing the thread
Provides a class that implements interface Runnable as the Thread target object. When initializing a Thread class or Thread subclass Thread object, it passes the target object to this Thread instance, the thread body provided by the target object
class RunnableImpl implements Runnable{public void run(){for(int i = 0 ; i < 100 ; i ++ ;){System.out.println("Runnable-->" + i);}}}
Class Test {public static void main (String args []) {// generate a Runnable interface implementation class Object RunnableImpl ri = new RunnableImpl (); // generate a Thread object, and pass the Runnable interface implementation class object as a parameter to the Thread object Thread t = new Thread (); // notify the Thread object and execute the start method t. start ();}}
In the actual development process, the second method is more inclined, because the first method only has one chance to inherit the Thread, and it cannot inherit other methods (single inheritance)
2. Common methods for controlling threads
. Interrupt thread
-- Thread. sleep (); // Thread. sleep (2000); in the thread body, you need to set a parameter (2000 ms) after sleep (2000), it will take a short time to run, because the thread needs to seize the CPU
Test:
class RunnableImpl implements Runnable{public void run(){for(int i = 0 ; i < 100 ; i ++ ;){System.out.println("Runnable-->" + i);if(i == 50){try{Thread.sleep(2000);}catch(Exception e){System.out.println(e);}}}}}
Class Test {public static void main (String args []) {// generate a Runnable interface implementation class Object RunnableImpl ri = new RunnableImpl (); // generate a Thread object, and pass the Runnable interface implementation class object as a parameter to the Thread object Thread t = new Thread (); // notify the Thread object and execute the start method t. start ();}}
-- Thread. yield (); // execute this line to automatically let out the CPU, and then the two threads simultaneously seize the CPU, it is possible that this Thread grabbed the CPU
. Set thread priority
-- GetPriority ();
-- SetPriority ();
Class Test {public static void main (String args []) {// generate a Runnable interface implementation class Object RunnableImpl ri = new RunnableImpl (); // generate a Thread object, and pass the Runnable interface implementation class object as a parameter to the Thread object // The maximum priority of the Thread is 10, the minimum is 1, you can use the static constants provided by the Thread to set the priority of the Thread. // note: the higher the priority of the Thread, the higher the execution probability (note that the Thread is probably not necessarily executed first) // t. setPriority (Thread. MAX_PRIORITY); // sets the maximum priority t. setPriority (Thread. MIN_PRIORITY); // sets the minimum priority Thread t = new Thread (); // notifies the Thread object and executes the start method t. start (); System. out. println (t. getPriority ());}}