编程知识 cdmana.com

Java learning notes -- multithreading

The first way to create a thread : Inherit Thread class

  • step :
    ① Define class inheritance Thread
    ② make carbon copies Thread Class run Method , Purpose : Store custom code in run In the method , Let the thread run
    ③ Calling thread's start Method , This method has two functions : Start thread , call run Method


  • Thread Why cover run Methods? ?
    Thread Class is used to describe threads , This class defines a function , Used to store the code the thread will run , The storage function is run Method , in other words Thread Class run Method , Used to store the code the thread will run .

 Code example 
class Test_thread extends Thread{
   
   
    public void run(){
   
   
        for(int x=0;x<20;x++)
            System.out.println(this.getName()+" run---"+x);
    }
}
class  Threads  {
   
   
    public static void main(String[] args) {
   
   
        Test_thread t1=new Test_thread();
        Test_thread t2=new Test_thread();
        t1.start();
        t2.start();
        for(int x=0;x<20;x++)
            System.out.println("main---"+x);
    }
}

The second way to create threads : Realization Runnable Interface

  • step :
    ① Implementation class implementation Runnable Interface
    ② Cover Runnable Interface run Method , Store the code to be run by the thread in the run In the method
    ③ adopt Thread Class to create thread objects
    ④ take Runnable The subclass object of the interface is passed to as an actual parameter Thread Class constructor ,
    ⑤ call Thread Class start Method to open the thread and call Runnable Interface subclass run Method




  • Why would you Runnable The subclass object of the interface is passed to Thread Constructor for ,
    because , Self defined run The object of the method is Runnable Interface subclass object ,
    So let the thread specify the run Method , It is necessary to make it clear that run Method belongs to

  • What's the difference between implementation and inheritance ?
    Benefits of implementation , The limitation of single inheritance is avoided
    The way of inheritance benefits , Set up a way to use it

  • The difference between the two ways :
    Threads Thread: Thread code storage Thread A subclass run In the method
    Realization Runnable: The thread code exists in the subclass of the interface run In the method

/*
 demand : Simple ticketing procedures . Multiple windows buy tickets at the same time 
*/
class Ticket implements Runnable{
   
    //extends Thread{
   
    
    private int tick=50;
    public void run(){
   
    
        while(true)
            if(tick>0)
                System.out.println(Thread.currentThread().getName()+"---sale: "+tick--);
    }
}
public class thread_example_2 {
   
    
    public static void main(String[] args) {
   
    
        Ticket t=new Ticket();
        Thread t1=new Thread(t);
        Thread t2=new Thread(t);
        Thread t3=new Thread(t);
        Thread t4=new Thread(t);
        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }
}

Security of multithreading

/*
 demand : Simple ticketing procedures . Multiple windows buy tickets at the same time 
*/
class Ticket implements Runnable{
   
     //extends Thread{
   
     
    private int tick=50;
    public void run(){
   
     
        while(true)
            if (tick > 0) {
   
     
            	try {
   
     
            		Thread.sleep(10);
            	} catch (Exception e) {
   
     
            	}
            	System.out.println(Thread.currentThread().getName() + "---sale: " + tick--);
            }
    }
}
public class thread_example_2 {
   
     
    public static void main(String[] args) {
   
     
        Ticket t=new Ticket();
        Thread t1=new Thread(t);
        Thread t2=new Thread(t);
        Thread t3=new Thread(t);
        Thread t4=new Thread(t);
        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }
}

By analyzing the code above , Find out , Print out 0、-1、-2 Waiting for the wrong ticket .
There are security problems with multithreading .

  • The cause of the problem :
    When multiple statements are operating on the same thread to share data , A thread only partially executes multiple statements , It's not finished , Another thread participates in the execution , Errors that cause shared data .
  • terms of settlement :
    Statements that share data for multiple operations , Only one thread can be executed , In the process of execution , Other threads are not allowed to participate in execution .

Multithread synchronization code block

Java For multithreading security issues provide professional solutions , It's synchronization code block .

synchronized( object ){
Code to be synchronized
}

  • Objects are like locks , The thread holding the lock can execute in synchronization ; There is no thread holding the lock, even if it gets CPU The enforcement of , Can't execute
  • The premise of synchronization :
    ① There must be two or more threads ;
    ② It must be multiple threads using the same lock , It must be ensured that only one thread is running in the synchronization .

benefits : It solves the security problem of multithreading
disadvantages : Multiple threads need to determine locks , It consumes more resources .

/*
 demand : Simple ticketing procedures . Multiple windows buy tickets at the same time 
*/
class Ticket implements Runnable{
   
      //extends Thread{
   
      
    private int tick=50;
    Object obj=new Object();
    public void run() {
   
      
        while (true)
            synchronized (obj) {
   
      
                if (tick > 0) {
   
      
                    try {
   
      
                        Thread.sleep(10);
                    } catch (Exception e) {
   
      
                    }
                    System.out.println(Thread.currentThread().getName() + "---sale: " + tick--);
                }
            }
    }
}
public class thread_example_2 {
   
      
    public static void main(String[] args) {
   
      
        Ticket t=new Ticket();
        Thread t1=new Thread(t);
        Thread t2=new Thread(t);
        Thread t3=new Thread(t);
        Thread t4=new Thread(t);
        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }
}

Multithread synchronization function

  • How to judge whether the target program has security problems ? If there is , How to solve ?
    ① Identify which code is multithreaded ;
    ② Clearly share data ;
    ③ Make sure that the statements in the multithreaded code operate on shared data .


Functions need to be called by objects , Anonymous functions have a reference to their own object , Namely this.
So the lock used by the synchronization function is this

Static in memory means that there is no such object in memory , But there must be a bytecode file object for that class ( Class name .class).
So the static synchronization method , The lock used is the bytecode file object of the class where the method is located Class name .class

/*
 demand : Simple ticketing procedures . Multiple windows buy tickets at the same time 
*/
class Ticket implements Runnable{
   
       //extends Thread{
   
       
    private int tick=50;//public static int tick=50;
    boolean flag=true;
    public void run() {
   
       
        if(flag) {
   
       
            while (true)
                synchronized (this) {
   
       //synchronized(Ticket.class)
                    if (tick > 0) {
   
       
                        try {
   
       
                            Thread.sleep(10);
                        } catch (Exception e) {
   
       
                        }
                        System.out.println(Thread.currentThread().getName() + "---sale: " + tick--);
                    }
                }
        }
        else
            while(true)
                show();
    }
    public synchronized void show(){
   
       
        if (tick > 0) {
   
       
            try {
   
       
                Thread.sleep(10);
            } catch (Exception e) {
   
       
            }
            System.out.println(Thread.currentThread().getName() + "---sale: " + tick--);
        }
    }
}
public class thread_example_2 {
   
       
    public static void main(String[] args) {
   
       
        Ticket t=new Ticket();
        Thread t1=new Thread(t);
        Thread t2=new Thread(t);
        t1.start();
        try{
   
       Thread.sleep(10);}catch(Exception e){
   
       }
        t.flag=false;
        t2.start();

    }
}

Multi thread deadlock

 Code example 
class Test implements Runnable{
   
        
    private boolean flag;
    Test(boolean flag){
   
        
        this.flag=flag;
    }
    public void run(){
   
        
        if(flag){
   
        
            synchronized (Mylock.locka){
   
        
                System.out.println("if locka");
                synchronized (Mylock.lockb) {
   
        
                    System.out.println("if lockb");
                }
            }
        }
        else{
   
        
            synchronized (Mylock.lockb){
   
        
                System.out.println("else lockb");
                synchronized (Mylock.locka) {
   
        
                    System.out.println("else locka");
                }
            }
        }
    }
}
class Mylock{
   
        
    static Object locka=new Object();
    static Object lockb=new Object();
}
class DeadTest{
   
        
    public static void main(String[] args) {
   
        
        Thread t1=new Thread(new Test(true));
        Thread t2=new Thread(new Test(false));
        t1.start();
        t2.start();
    }
}

版权声明
本文为[osc_ 8grrbqh4]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201225095555709c.html

Scroll to Top