Detailed control of Java threads

  • 2020-04-01 03:31:25
  • OfStack

1. Join the thread :

During thread execution, there are times when you want another thread to execute first, such as splitting a big problem into many small problems, assigning a thread to each small problem, and then letting the main thread proceed after all the small problems have been dealt with. At this point we can call the join () method of other threads in the main thread to block the calling thread (in this case the primary thread).

Sample code:


 package org.frzh.thread;
 
 public class JoinThread extends Thread{
     //Provides a parameter constructor to set the name of the thread
     public JoinThread(String name) {
         super(name);
     }
    
     public void run() {
         for (int i = 0; i < 100; i++) {
             System.out.println(getName() + " " + i);
         }
     }
    
     public static void main(String[] args) {
         //Initiator subthread
         new JoinThread(" A new thread ").start();
         for (int i = 0; i < 100; i++) {
             if (i == 20) {
                 JoinThread jt = new JoinThread(" be join The thread ");
                 jt.start();
                 //The main thread invokes the join method of the jt thread, so the main thread must wait for the jt to complete before executing
                 try {
                     jt.join();
                 } catch (InterruptedException e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
                 }
             }
             System.out.println(Thread.currentThread().getName() + " " +i);
         }
     }
 }

There were originally three sets of threads (two child threads and one main thread), and when I =20, the main thread was blocked and had to wait until the "joined thread" was finished before it had a chance to execute, so only two threads executed after that.

Three overloads of the join () method:

Join (): wait for the join thread to finish executing;

Join (long millis) : wait for the join thread to execute for the longest time of mills hao seconds, after which the join thread will not wait even if it has not finished executing;

Join (long millis, int nanos) : the maximum time to wait for the join thread to execute is millis milliseconds +nanos microseconds. This method is almost useless.

2: background threads :

There is a thread that runs in the background and whose job is to serve other threads. This thread is called a "background thread", "daemon thread", or "Sprite thread". When all foreground threads die, the background thread dies automatically.

Sample code:


 package org.frzh.thread;
 
 public class DaemonThread extends Thread{
     public void run() {
         for (int i = 0; i < 1000; i++) {
             System.out.println(getName() + " " +i);
         }
     }
    
     public static void main(String[] args) {
         DaemonThread dt = new DaemonThread();
         //Set this thread to background thread
         dt.setDaemon(true);
         dt.start();
         for (int i = 0; i < 10; i++) {
             System.out.println(Thread.currentThread().getName() + " " + i);
         }
         //When the foreground thread ends, the background thread dt also ends, so it cannot execute 999
     }
 }

The main thread is the foreground thread by default, the child thread created by the foreground thread is the foreground thread by default, and the child thread created by the background thread is the background thread by default.

3. Thread sleep:

The previous join method lets the calling thread wait for the join thread to finish executing before continuing, while the sleep () method lets the calling thread block for a while before re-entering the ready state to wait to be scheduled. Therefore, it is often used to suspend the execution of a program.

Sample code:


 package org.frzh.thread;
 
 import java.util.Date;
 
 public class SleepThread{
     public static void main(String[] args) {
         for (int i = 0; i < 10; i++) {
             System.out.println(" Current time: " + new Date());
             try {
                 Thread.sleep(1000);
             } catch (InterruptedException e) {
                 // TODO Auto-generated catch block
                 e.printStackTrace();
             }
         }
     }
 }

Two ways to overload the sleep () method:

Static void sleep (long millis) : causes the current thread to pause millis for milliseconds and enter a blocking state. This method is affected by the precision and accuracy of the system timer and thread scheduler.

Static void sleep (long millis, int nanos): pauses the mills for milliseconds +nanos microseconds and enters a blocking state, again affected by the accuracy and accuracy of the system timer and thread scheduler. Not really.

4. Thread concessions (yield) :

The yield () method is similar to the sleep method in that it can also pause the currently running thread, but it doesn't block the thread, it just puts it into the ready state (not blocked). The yield () method only gives a thread of the same or higher priority a chance to be executed, so a thread that calls the method may be rescheduled to continue execution.

Sample code:


 package org.frzh.thread;
 
 public class YieldThread extends Thread{
     public YieldThread() {
        
     }
     public YieldThread(String name) {
         super(name);
     }
     public void run() {
         for (int i = 0; i < 100; i++) {
             System.out.println(getName() + " " +i);
             if (i == 20) {
                 //Current thread concession
                 Thread.yield();
             }
         }
        
     }
    
     public static void main(String[] args) {
         //Start two concurrent threads
         YieldThread yt1 = new YieldThread(" senior ");
         //Set yt1 to the highest priority
         yt1.setPriority(Thread.MAX_PRIORITY);
         yt1.start();
         YieldThread yt2 = new YieldThread(" low-level ");
         yt2.setPriority(Thread.MIN_PRIORITY);
         yt2.start();
         /*
          * If no priority is given to the thread, the priority of the two threads is the same, so the two threads execute alternately when called yield Then it will let another thread execute;
          * However, after setting the above priority for each of the two threads, the advanced thread execution just begins, when i=20 , the call yield , but due to yield Methods will only
          * A thread of the same or higher priority is given the opportunity to execute, so it is still a high-level thread, not a low-level thread
          */
     }
 }

5: change the priority of the thread :

This is relatively simple by calling the instance method setPriority(int priority). Each thread defaults to the same priority as its parent, and the main thread defaults to a normal priority (5). Java provides 1 to 10 priorities, and you can also use three static constants:

MAX_PRIORITY: 10

MIN_PRIORITY: 1.

NORM_PRIORITY: 5

Note that although Java provides 10 priorities, different systems support different priorities, so avoid using Numbers between 1 and 10 directly and use static constants to ensure good portability.


Related articles: