The use of Java multithreading is described in detail

  • 2020-11-03 22:07:02
  • OfStack

Java multithreading is described in detail

If you don't have a thorough understanding of the mechanics of multithreading in Java, this article will help you to have a more thorough understanding of how Java works and how it works.

1. Create threads

There are two ways to create threads in Java: using the Thread class and using the Runnable interface. An instance of Thread needs to be created when using the Runnable interface. Therefore, whether a thread is created through the Thread class or the Runnable interface, an instance of the Thread class or its subclasses must be created. Thread constructor:


public Thread( );
public Thread(Runnable target);
public Thread(String name);
public Thread(Runnable target, String name);
public Thread(ThreadGroup group, Runnable target);
public Thread(ThreadGroup group, String name);
public Thread(ThreadGroup group, Runnable target, String name);
public Thread(ThreadGroup group, Runnable target, String name, long stackSize);

Method 1: Inherit from the Thread class and override the run method


public class ThreadDemo1 {
   public static void main(String[] args){
     Demo d = new Demo();
     d.start();
     for(int i=0;i<60;i++){
       System.out.println(Thread.currentThread().getName()+i);
     }

   }
 }
 class Demo extends Thread{
   public void run(){
     for(int i=0;i<60;i++){
       System.out.println(Thread.currentThread().getName()+i);
     }
   }
 }

Method 2:


public class ThreadDemo2 {
  public static void main(String[] args){
    Demo2 d =new Demo2();
    Thread t = new Thread(d);
    t.start();
    for(int x=0;x<60;x++){
      System.out.println(Thread.currentThread().getName()+x);
    }
  }
}
class Demo2 implements Runnable{
  public void run(){
    for(int x=0;x<60;x++){
      System.out.println(Thread.currentThread().getName()+x);
    }
  }
}

2. The lifetime of the thread

Like a human being, a thread also goes through four different states: start (wait), run, hang, and stop. All four states can be controlled through methods in the Thread class. The methods associated with these four states in the Thread class are given below.


//  To start a thread 
publicvoid start( );
publicvoid run( );
//  Suspend and wake the thread 
publicvoid resume( );   //  Not recommended 
publicvoid suspend( );  //  Not recommended 
publicstaticvoid sleep(long millis);
publicstaticvoid sleep(long millis, int nanos);
//  Termination of the thread 
publicvoid stop( );    //  Not recommended 
publicvoid interrupt( );
//  Get the thread state 
publicboolean isAlive( );
publicboolean isInterrupted( );
publicstaticboolean interrupted( );
// join methods 
publicvoid join( ) throws InterruptedException;

Instead of executing the code in the run method immediately after it is created, the thread is in a wait state. When a thread is in a waiting state, the methods of the Thread class can be used to set various attributes of the thread, such as the priority of the thread (setPriority), the name of the thread (setName), and the type of the thread (setDaemon).

When the start method is called, the thread begins to execute the code in the run method. The thread enters the run state. The isAlive method of the Thread class can be used to determine whether a thread is running. When the thread is running, isAlive returns true, and when isAlive returns false, the thread may be in a wait state or a stop state. The following code demonstrates the switch between the create, run, and stop states of a thread and prints the corresponding isAlive return value.

But the thread starts to execute the run method, and the thread does not exit until the run method finishes executing. There are, however, two ways to make a thread temporarily stop executing while it is executing. The two methods are suspend and sleep. After using suspend to suspend a thread, the resume method can be used to wake it up. After using sleep to sleep a thread, it can only be put into the ready state after the set time (after the end of sleep, the thread will not be executed immediately, but enter the ready state, waiting for the system to schedule).

There are two points to note when using the sleep method:

1. The sleep method has two overload forms, one of which can set not only milliseconds, but nanoseconds (1,000,000 nanoseconds = 1 millisecond). However, the Java virtual machine on most operating system platforms is not accurate to nanoseconds, so if the sleep virtual machine is set to nanoseconds, the Java virtual machine will take the nearest milliseconds to this value.

2. Use throws or try{... when using the sleep method. } catch {... }. Because the run method cannot use throws, only try{... } catch {... }. sleep throws an InterruptedException exception when the thread is interrupted using the interrupt method during thread sleep. The sleep method is defined as follows:


publicstaticvoid sleep(long millis) throws InterruptedException
publicstaticvoid sleep(long millis, int nanos) throws InterruptedException

There are three ways to terminate a thread.

1. Use the exit flag to make the thread exit normally, that is, when the run method completes, the thread terminates.

2. Use the stop method to force the termination of a thread (this method is not recommended as stop, like suspend and resume1, can also have unexpected results).

3. Use the interrupt method to break the thread.

1. Use the exit flag to terminate the thread

When the run method finishes executing, the thread exits. But sometimes the run method is never finished. Such as using threads in server-side programs to listen for client requests, or other tasks that need to be processed in a loop. In this case, 1 would normally put these tasks in a loop, such as the while loop. If you want the loop to run forever, use while(true){... } to deal with. However, the most direct way to get the while loop to exit under a specific condition of 1 is to set a flag of type boolean and control whether the while loop exits by setting this flag as true or false. An example of terminating a thread using the exit flag is given below.

The function of the join method is to make the thread that executes asynchronously execute synchronously. That is, when the start method of the thread instance is called, it returns immediately. If you need to use a value calculated by the thread after calling the start method, you must use the join method. Without the join method, there is no guarantee that thread 1 will finish executing a statement after the start method. With the join method, the program does not proceed until the thread exits. The following code demonstrates the use of join.

3. Multithreaded security issues

Problem cause: When multiple statements are operating and share data with one thread, one thread executes only one part of multiple statements, and another thread participates in the execution, resulting in the error of sharing data.

Solution: For statements in which multiple operations share data, only one thread can complete the execution, and no other thread executes during the execution.

Synchronous code block:


public class ThreadDemo3 {
  public static void main(String[] args){
    Ticket t =new Ticket();
    Thread t1 = new Thread(t," window 1");
    Thread t2 = new Thread(t," window 2");
    Thread t3 = new Thread(t," window 3");
    Thread t4 = new Thread(t," window 4");
    t1.start();
    t2.start();
    t3.start();
    t4.start();
  }
}
class Ticket implements Runnable{
  private int ticket =400;
  public void run(){
    while(true){
      synchronized (new Object()) {
        try {
          Thread.sleep(1);
        } catch (InterruptedException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
        if(ticket<=0)
          break;
        System.out.println(Thread.currentThread().getName()+"--- sell "+ticket--);
      }
    }
  }
}

Synchronization function


public class ThreadDemo3 {
  public static void main(String[] args){
    Ticket t =new Ticket();
    Thread t1 = new Thread(t," window 1");
    Thread t2 = new Thread(t," window 2");
    Thread t3 = new Thread(t," window 3");
    Thread t4 = new Thread(t," window 4");
    t1.start();
    t2.start();
    t3.start();
    t4.start();
  }
}
class Ticket implements Runnable{
  private int ticket = 4000;
  public synchronized void saleTicket(){
    if(ticket>0)
      System.out.println(Thread.currentThread().getName()+" sold "+ticket--);

  }
  public void run(){
    while(true){
      saleTicket();
    }
  }
}

The synchronization function lock is this and the static synchronization function lock is class

Communication between threads


public class ThreadDemo3 {
  public static void main(String[] args){
    class Person{
      public String name;
      private String gender;
      public void set(String name,String gender){
        this.name =name;
        this.gender =gender;
      }
      public void get(){
        System.out.println(this.name+"...."+this.gender);
      }
    }
    final Person p =new Person();
    new Thread(new Runnable(){
      public void run(){
        int x=0;
        while(true){
          if(x==0){
            p.set(" zhang 3", " male ");
          }else{
            p.set("lili", "nv");
          }
          x=(x+1)%2;
        }
      }
    }).start();
    new Thread(new Runnable(){
      public void run(){
        while(true){
          p.get();
        }
      }
    }).start();
  }
}
/*
 zhang 3.... male 
 zhang 3.... male 
lili....nv
lili.... male 
 zhang 3....nv
lili.... male 
*/

Modify the above code


public class ThreadDemo3 {
   public static void main(String[] args){
     class Person{
       public String name;
       private String gender;
       public void set(String name,String gender){
         this.name =name;
         this.gender =gender;
       }
       public void get(){
         System.out.println(this.name+"...."+this.gender);
       }
     }
     final Person p =new Person();
     new Thread(new Runnable(){
       public void run(){
         int x=0;
         while(true){
           synchronized (p) {
             if(x==0){
               p.set(" zhang 3", " male ");
             }else{
               p.set("lili", "nv");
             }
             x=(x+1)%2;  
           }

         }
       }
     }).start();
     new Thread(new Runnable(){
       public void run(){
         while(true){
           synchronized (p) {
             p.get();
           }
         }
       }
     }).start();
   }

 }
 /*
 lili....nv
 lili....nv
 lili....nv
 lili....nv
 lili....nv
 lili....nv
  zhang 3.... male 
  zhang 3.... male 
  zhang 3.... male 
  zhang 3.... male 
 */

Wait and wake mechanism


/*
 * Threads wait for a wake-up mechanism 
 * Waiting and waking must be the same thing 1 The lock  
 */
public class ThreadDemo3 {
  private static boolean flags =false;
  public static void main(String[] args){
    class Person{
      public String name;
      private String gender;
      public void set(String name,String gender){
        this.name =name;
        this.gender =gender;
      }
      public void get(){
        System.out.println(this.name+"...."+this.gender);
      }
    }
    final Person p =new Person();
    new Thread(new Runnable(){
      public void run(){
        int x=0;
        while(true){
          synchronized (p) {
            if(flags)
              try {
                p.wait();
              } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
              };
            if(x==0){
              p.set(" zhang 3", " male ");
            }else{
              p.set("lili", "nv");
            }
            x=(x+1)%2;
            flags =true;
            p.notifyAll();
          }
        }
      }
    }).start();
    new Thread(new Runnable(){
      public void run(){
        while(true){
          synchronized (p) {
            if(!flags)
              try {
                p.wait();
              } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
              };
            p.get();
            flags =false;
            p.notifyAll();
            }
        }
      }
    }).start();
  }
}

Mechanism of production and consumption 1


public class ThreadDemo1 {
   public static void main(String[] args){
     Demo d = new Demo();
     d.start();
     for(int i=0;i<60;i++){
       System.out.println(Thread.currentThread().getName()+i);
     }

   }
 }
 class Demo extends Thread{
   public void run(){
     for(int i=0;i<60;i++){
       System.out.println(Thread.currentThread().getName()+i);
     }
   }
 }

0

Mechanism of production and consumption ii


public class ThreadDemo1 {
   public static void main(String[] args){
     Demo d = new Demo();
     d.start();
     for(int i=0;i<60;i++){
       System.out.println(Thread.currentThread().getName()+i);
     }

   }
 }
 class Demo extends Thread{
   public void run(){
     for(int i=0;i<60;i++){
       System.out.println(Thread.currentThread().getName()+i);
     }
   }
 }

1

Above is the use of java multithreading method, if you have any questions, please leave a message or to this site community exchange discussion, thank you for reading, I hope to help you, thank you for your support to this site!


Related articles: