1. Multithread security 2. Waiting for wake-up mechanism

Posted by ZaphodQB on Wed, 26 Jun 2019 01:14:08 +0200

01 Thread Operation Sharing Data Security Issues

* A: Thread Operation Sharing Data Security

If there are multiple threads running at the same time, these threads may run the code at the same time.
The result of each run of the program is the same as that of single thread, and the value of other variables is the same as expected, which is thread-safe.

02 Ticket Sales Case

* A: The case of ticket sales

 /*
  * Multi-threaded concurrent access to the same data resource
  * 3 Threads, a ticket resource, for sale
  */
 public class ThreadDemo {
  public static void main(String[] args) {
    //Creating Runnable Interface to Implement Class Objects
    Tickets t = new Tickets();
    //Create three Thread class objects and pass Runnable interface implementation class
    Thread t0 = new Thread(t);
    Thread t1 = new Thread(t);
    Thread t2 = new Thread(t);
    
    t0.start();
    t1.start();
    t2.start();
    
  }
 }

 public class Tickets implements Runnable{
  
  //Define the source of tickets for sale
  private int ticket = 100;
  private Object obj = new Object();
  
  public void run(){
    while(true){
   
        if( ticket > 0){
          
          System.out.println(Thread.currentThread().getName()+" Selling "+ticket--);
        }
      
    }
  }
 }

03 Thread Safety Problem Initiated

* A: Thread security issues

/*
 * Multi-threaded concurrent access to the same data resource
 * 3 Threads, a ticket resource, for sale
 */
public class ThreadDemo {
 public static void main(String[] args) {
   //Creating Runnable Interface to Implement Class Objects
   Tickets t = new Tickets();
   //Create three Thread class objects and pass Runnable interface implementation class
   Thread t0 = new Thread(t);
   Thread t1 = new Thread(t);
   Thread t2 = new Thread(t);
   
   t0.start();
   t1.start();
   t2.start();
   
 }
}
/*
 *  Thread hibernation causes security problems
 */
public class Tickets implements Runnable{
 
 //Define the source of tickets for sale
 private int ticket = 100;
 private Object obj = new Object();
 
 public void run(){
   while(true){

     //Judgment of the number of votes, greater than 0, can be sold, variable - operation
       if( ticket > 0){
         try{
            Thread.sleep(10); //Hibernation gives other threads an opportunity to execute
         }catch(Exception ex){}
         System.out.println(Thread.currentThread().getName()+" Selling "+ticket--);
       }
   }
 }
}

04 Synchronized Code Block Solves Thread Safety Problem

* A: Synchronizing code blocks to solve thread security problems

  *A:Case of ticket sales
      /*
       * Multi-threaded concurrent access to the same data resource
       * 3 Threads, a ticket resource, for sale
       */
      public class ThreadDemo {
       public static void main(String[] args) {
         //Creating Runnable Interface to Implement Class Objects
         Tickets t = new Tickets();
         //Create three Thread class objects and pass Runnable interface implementation class
         Thread t0 = new Thread(t);
         Thread t1 = new Thread(t);
         Thread t2 = new Thread(t);
         
         t0.start();
         t1.start();
         t2.start();
         
       }
      }
      /*
       *  Thread hibernation causes security problems
       *  Solve security issues, Java programs, provide technology, synchronization technology
       *  Formula:
       *    synchronized(Arbitrary object){
       *      Shared data to be manipulated by threads
       *    }
       *    Synchronized code block
       */
      public class Tickets implements Runnable{
       
       //Define the source of tickets for sale
       private int ticket = 100;
       private Object obj = new Object();
       
       public void run(){
         while(true){
           //Threads share data to ensure security and add synchronous code blocks
           synchronized(obj){
           //Judgment of the number of votes, greater than 0, can be sold, variable - operation
             if( ticket > 0){
               try{
                  Thread.sleep(10);
               }catch(Exception ex){}
               System.out.println(Thread.currentThread().getName()+" Selling "+ticket--);
             }
           }
         }
       }
      }

Execution Principle of Synchronized Code Block 05

A: Execution Principle of Synchronized Code Block

 Synchronized block: Add synchronized to the block declaration
 synchronized (lock object){
   Code that may cause thread security problems
 }
 Lock objects in synchronous code blocks can be arbitrary objects; however, when multiple threads are involved, the same lock object is needed to ensure thread safety.

======================= The second class begins=============================================

06 Synchronized Toilet Up Principle

* A: The Principle of Synchronized Toilet Access

a: No synchronization: Threads are disturbed during execution
   Threads as Adults
   Thread execution code is to go to a toilet
  The first person was going to the toilet, half way up, and was pulled out by another person.
b: Using synchronization:
   Threads as Adults
   Thread execution code is to go to a toilet
   Locks are compared to toilet doors
  The first person goes to the toilet and locks the door.
  The second man went to the toilet and saw that the door was locked and waited for the first person to finish before going to the toilet.

07 Synchronization Method

* A: Synchronization method:
/*

  • Multi-threaded concurrent access to the same data resource

  • Three threads, one ticket resource, for sale
    */

public class ThreadDemo {

public static void main(String[] args) {
  //Creating Runnable Interface to Implement Class Objects
  Tickets t = new Tickets();
  //Create three Thread class objects and pass Runnable interface implementation class
  Thread t0 = new Thread(t);
  Thread t1 = new Thread(t);
  Thread t2 = new Thread(t);
  
  t0.start();
  t1.start();
  t2.start();
  
}

}

* A: Synchronization method

 /*
  *  Using Synchronization Method to Solve Thread Security Problem
  *  Benefits: Simple code
  *  Extract threads to share data, synchronize, and extract data into a method
  *  On the method declaration, add the synchronization keyword
  *  
  *  Questions:
  *    Does the synchronization method have a lock? Surely, the object lock in the synchronization method refers to this kind of object.
  *    If the method is static, is synchronization locked, absolutely not this?
  *    Locks are the class itself. class attribute
  *    Static method, synchronous lock, is the class name. class attribute
  */
 public class Tickets implements Runnable{

  //Define the source of tickets for sale
  private  int ticket = 100;
  
  public void run(){
    while(true){
      payTicket();
    }
  }
  
  public  synchronized void payTicket(){  
      if( ticket > 0){
        try{
           Thread.sleep(10);
        }catch(Exception ex){}
        System.out.println(Thread.currentThread().getName()+" Selling "+ticket--);
      }
    
  }
 }

08JDK 1.5 New Feature Lock Interface

* A: JDK 1.5 New Feature Lock Interface

    Looking at API s and Lock interface descriptions, Lock implementations provide a wider range of locking operations than can be obtained using synchronized methods and statements.
  Common methods in Lock interface
        void lock()
        void unlock()
  Lock provides a more object-oriented lock, in which more functions are provided to manipulate locks.
  We use Lock interface, lock() method and unlock() method instead of synchronization, to Ticket in movie ticket sales cases.

09Lock Interface Improvement Ticketing Case

* A: Case Study of Lock Interface Improvement in Ticket Selling

  /*
   * Multi-threaded concurrent access to the same data resource
   * 3 Threads, a ticket resource, for sale
   */
  public class ThreadDemo {
    public static void main(String[] args) {
      //Creating Runnable Interface to Implement Class Objects
      Tickets t = new Tickets();
      //Create three Thread class objects and pass Runnable interface implementation class
      Thread t0 = new Thread(t);
      Thread t1 = new Thread(t);
      Thread t2 = new Thread(t);
      
      t0.start();
      t1.start();
      t2.start();
      
    }
  }
  /*
   *  Using JDK 1.5 interface Lock to replace synchronous code block to achieve thread security
   *  Lock Interface method:
   *     lock() Acquisition locks
   *     unlock()Release lock
   *  Implementation class ReentrantLock
   */
  public class Tickets implements Runnable{
    
    //Define the source of tickets for sale
    private int ticket = 100;
    //Create an implementation class object of the Lock interface at the member location of the class
    private Lock lock = new ReentrantLock();
    
    public void run(){
      while(true){
        //Call Lock interface method lock to get locks
          lock.lock();
        //Judgment of the number of votes, greater than 0, can be sold, variable - operation
          if( ticket > 0){
            try{
               Thread.sleep(10);
               System.out.println(Thread.currentThread().getName()+" Selling "+ticket--);
            }catch(Exception ex){
              
            }finally{
              //Release the lock and call the Lock interface method unlock
              lock.unlock();
            }
          }
      }
    }
  }

======================= The third lesson begins=============================================

Deadlock Principle of 10 Threads

* A: Thread Deadlock Principle

 When multiple synchronizations (locks) occur in a thread task, if other synchronizations are nested in the synchronization. At this time, it is easy to trigger a phenomenon: program appears infinite waiting, which we call deadlock. If this situation can be avoided, it can be avoided.
    synchronzied(A lock){
        synchronized(B lock){
                  
        }
    }

Deadlock Code Implementation of 11 Threads

* A: Implementation of deadlock code for threads

   public class DeadLock implements Runnable{
    private int i = 0;
    public void run(){
      while(true){
        if(i%2==0){
          //First enter A synchronization, then B synchronization
          synchronized(LockA.locka){
            System.out.println("if...locka");
            synchronized(LockB.lockb){
              System.out.println("if...lockb");
            }
          }
        }else{
          //First enter B synchronization, then enter A synchronization
          synchronized(LockB.lockb){
            System.out.println("else...lockb");
            synchronized(LockA.locka){
              System.out.println("else...locka");
            }
          }
        }
        i++;
      }
    }
   }

  public class DeadLockDemo {
    public static void main(String[] args) {
      DeadLock dead = new DeadLock();
      Thread t0 = new Thread(dead);
      Thread t1 = new Thread(dead);
      t0.start();
      t1.start();
    }
  }
  public class LockA {
    private LockA(){}
    
    public  static final LockA locka = new LockA();
  }

  
  public class LockB {
    private LockB(){}
    
    public static final LockB lockb = new LockB();
  }

### 12 Threads Waiting and Waking Case
* A: A Case Study of Thread Waiting and Waking

 Waiting for wake-up mechanisms involves methods:
   wait (): wait, release the execution qualifications and execution rights of the executing thread, and store them in the thread pool.
   Notfy (): Wake up, wake up a thread in the thread pool wait ing (), wake up one at a time, and it's arbitrary.
   NotfyAll (): Wake up all: You can wake up all wait() threads in the thread pool.
   In fact, the so-called wake-up means that the thread in the thread pool is qualified for execution. It must be noted that these methods are effective in synchronization. At the same time, these methods must indicate the locks they belong to when they are used, so as to determine which thread on which locks these methods operate.

13 Thread Waiting and Waking Case Resource Class Writing

* A: Writing resource class for thread waiting and wake-up cases

/*
 *  Define resource classes with two member variables
 *  name,sex
 *  There are also two threads that operate on variables in the resource
 *  1 Assignment of name and age
 *  2 Output printing of variables for name and age
 */
public class Resource {
  public String name;
  public String sex;
}

14 Threads Waiting and Waking Case Input and Output Threads

A: Thread Waiting and Waking Case Input and Output Threads

 /*
   *  Input threads assign values to member variables in Resource object resources
   *  One assignment Zhang San, male
   *  Next assignment lisi,nv
 */
  public class Input implements Runnable {
    private Resource r=new Resource();
   
    public void run() {
      int i=0;
      while(true){
        if(i%2==0){
           r.name="Zhang San";
           r.sex="male";
         }else{
            r.name="lisi";
            r.sex="female";
          }
        i++;
      }
    }
  }

  /*
   *  Output threads, member variables in Resource object resources, output values
   */
  public class Output implements Runnable {
    private Resource r=new Resource() ;
     
    public void run() {
      while(true){
         System.out.println(r.name+"..."+r.sex); 
        }
      }
  }

================================= Lesson 4=========================================

15 Threads Waiting and Waking Case Test Class

A: Thread Waiting and Waking Case Test Class

  /*
   *  Open input and output threads to assign and print values
   */
  public class ThreadDemo{
    public static void main(String[] args) {
      
      Resource r = new Resource();
      
      Input in = new Input();
      Output out = new Output();
      
      Thread tin = new Thread(in);
      Thread tout = new Thread(out);
      
      tin.start();
      tout.start();
    }
  }

16 Threads Waiting and Waking Case null Value Solution

A: Thread Waiting and Waking Case null Value Solution

    /*
    *  Input threads assign values to member variables in Resource object resources
    *  One assignment Zhang San, male
    *  Next assignment lisi,nv
  */
   public class Input implements Runnable {
     private Resource r;
     public Input(Resource r){
       this.r=r;
     }
    
     public void run() {
       int i=0;
       while(true){
         if(i%2==0){
            r.name="Zhang San";
            r.sex="male";
          }else{
             r.name="lisi"
             r.sex="female"
           }
         i++;
       }
     }
   }

   /*
    *  Output threads, member variables in Resource object resources, output values
    */ 
   public class Output implements Runnable {
     private Resource r;
     public Output(Resource r){
        this.r=r;
     } 
     public void run() {
       while(true){
          System.out.println(r.name+"..."+r.sex); 
         }
       }
     }

   }
   /*
    *  Open input and output threads to assign and print values
    */
   public class ThreadDemo{
     public static void main(String[] args) {
       
       Resource r = new Resource();
       
       Input in = new Input(r);
       Output out = new Output(r);
       
       Thread tin = new Thread(in);
       Thread tout = new Thread(out);
       
       tin.start();
       tout.start();
     }
   }

17 Threads Waiting and Waking Case Data Security Solution

A:Thread Waiting and Waking Case Data Security Solution
        /*
          *  Input threads assign values to member variables in Resource object resources
          *  One assignment Zhang San, male
          *  Next assignment lisi,nv
        */
         public class Input implements Runnable {
           private Resource r;
           public Input(Resource r){
             this.r=r;
           }
          
           public void run() {
             int i=0;
             while(true){
              synchronized(r){
               if(i%2==0){
                  r.name="Zhang San";
                  r.sex="male";
                }else{
                   r.name="lisi"
                   r.sex="female"
                 }
               i++;
             }

           }
         }

         /*
          *  Output threads, member variables in Resource object resources, output values
          */ 
         public class Output implements Runnable {
           private Resource r;
           public Output(Resource r){
              this.r=r;
           } 
           public void run() {
             while(true){
                synchronized(r){
                 System.out.println(r.name+"..."+r.sex); 
                }
               }
             }
           }

         }
         /*
          *  Open input and output threads to assign and print values
          */
         public class ThreadDemo{
           public static void main(String[] args) {
             
             Resource r = new Resource();
             
             Input in = new Input(r);
             Output out = new Output(r);
             
             Thread tin = new Thread(in);
             Thread tout = new Thread(out);
             
             tin.start();
             tout.start();
           }
         }

Analysis of 18 Threads Waiting and Waking Case Communication

* A: Analysis of Communication between Thread Waiting and Wake-up Cases
    Input: After assignment, the execution method wait() waits forever
    Output: Print out variable values, wake up before output waits
    Enter notify(), wait() forever
    Input: After being waked up, the variable is reassigned. After assignment, the output thread notify() must be waked up.
         My own wait()

Implementation of 19 Thread Waiting and Waking Case

* Implementation of A Thread Waiting and Waking Case

 /*
  *  Define resource classes with two member variables
  *  name,sex
  *  There are also two threads that operate on variables in the resource
  *  1 Assignment of name and age
  *  2 Output printing of variables for name and age
  */
 public class Resource {
  public String name;
  public String sex;
  public boolean flag = false;
 }

 /*
  *  Input threads assign values to member variables in Resource object resources
  *  One assignment Zhang San, male
  *  Next assignment lisi,nv
  */
 public class Input implements Runnable {
  private Resource r ;
  
  public Input(Resource r){
    this.r = r;
  }
  
  public void run() {
    int i = 0 ;
    while(true){
      synchronized(r){
        //The tag is true, wait
          if(r.flag){
            try{r.wait();}catch(Exception ex){}
          }
        
        if(i%2==0){
          r.name = "Zhang San";
          r.sex = "male";
        }else{
          r.name = "lisi";
          r.sex = "nv";
        }
        //Wake up the other thread and change the marker to true
        r.flag = true;
        r.notify();
      }
      i++;
    }
  }

 }
 
 /*
  *  Output threads, member variables in Resource object resources, output values
  */
 public class Output implements Runnable {
  private Resource r ;
  
  public Output(Resource r){
    this.r = r;
  }
  public void run() {
    while(true){
      synchronized(r){  
        //Judgment flag, false, wait
      if(!r.flag){
        try{r.wait();}catch(Exception ex){}
        }
      System.out.println(r.name+".."+r.sex);
      //Change the tag to false to wake up the other thread
      r.flag = false;
      r.notify();
      }
    }
  }

 }

 /*
  *  Open input and output threads to assign and print values
  */
 public class ThreadDemo{
  public static void main(String[] args) {
    
    Resource r = new Resource();
    
    Input in = new Input(r);
    Output out = new Output(r);
    
    Thread tin = new Thread(in);
    Thread tout = new Thread(out);
    
    tin.start();
    tout.start();
  }
 }

20 eclipse problem

A:eclipse problem

Topics: Java JDK Attribute Eclipse