当前位置:网站首页>The principle and common methods of multithreading and the difference between thread and runnable

The principle and common methods of multithreading and the difference between thread and runnable

2022-04-23 15:45:00 Have a drink together

Multithreading principle

Random printing

CPU There are two execution paths ,CPU You have a choice , It will be executed later main Method It will be executed later run Method .
It can also be said that two threads , One main Threads One run Threads Ask for CPU The enforcement of ( execution time ) Whoever grabs it will execute the corresponding code
 Multi thread randomness print results

Multithreaded memory diagram

  1. main Method to create an object , Create objects and store them in heap memory ( The address value is assigned to the variable name 0x11)
  2. mt.**run()** Invocation time run Methods are pushed into the stack It's actually a single threaded program (main Threads , It'll be done first run Method then executes other methods in the main thread )
  3. mt.**start()** When called, it will open up a new stack space . perform run Method (run The method is not in main Threads execute , Instead, execute in the new stack space , If it were start It will open up another stack space and another thread )

Yes cpu for ,cpu You have the right to choose It can be executed main Method 、 You can also perform two run Method .
The benefits of multithreading : When multithreading is executed , In stack memory , In fact, each execution thread has its own stack memory space , Multiple threads do not affect each other Stack pressing and spring stack .
 Multithreaded memory diagram

Thread Common methods of class

Get thread name getName()

public static void main(String[] args) {
    
    // establish Thread Subclass object of class 
    MyThread mt = new MyThread();
    // call start Method , Start a new thread , perform run Method 
    mt.start();

    new MyThread().start();
    new MyThread().start();

    // Chain programming 
    System.out.println(Thread.currentThread().getName());
}

/**  Get the name of the thread : 1. Use Thread Methods in class getName() String getName()  Returns the name of the thread . 2. You can get the currently executing thread first , Use methods in threads getName() Get the name of the thread  static Thread currentThread()  Returns a reference to the currently executing thread object . * @author zjq */
//  Define a Thread Subclasses of classes 
public class MyThread extends Thread{
    
    // rewrite Thread Class run Method , Set up thread tasks 
    @Override
    public void run() {
    
        // Get thread name 
        //String name = getName();
        //System.out.println(name);

        // Chain programming 
        System.out.println(Thread.currentThread().getName());
    }
}

Output is as follows :

main
Thread-2
Thread-0
Thread-1

Set the thread name setName() perhaps new Thread(“ Thread name ”)

  1. Use Thread Methods in class setName( name )
    void setName(String name) Change thread name , Make it and parameter name identical .

  2. Create a construction method with parameters , Parameter passing the name of the thread ; Call the parameter constructor of the parent class , Pass the thread name to the parent class , Let the parent class (Thread) Give the child thread a name

    Thread(String name) Assign a new Thread object .
    Code case :

// Enable multithreading 
MyThread mt = new MyThread();
mt.setName(" cockroach ");
mt.start();

// Enable multithreading 
new MyThread(" Wangcai ").start();

Pause the currently executing thread for the specified number of milliseconds sleep(long millis)

Code case :

public static void main(String[] args) {
    
        // Analog stopwatch 
        for (int i = 1; i <=60 ; i++) {
    
            System.out.println(i);

            // Use Thread Class sleep How to make the program sleep 1 Second 
            try {
    
                Thread.sleep(1000);
            } catch (InterruptedException e) {
    
                e.printStackTrace();
            }
        }
    }

🥧 The second way to create a multithreaded program - Realization Runnable Interface

Realization Runnable Interface to implement multithreading steps :

  1. Create a Runnable Implementation class of interface
  2. Override... In the implementation class Runnable Interface run Method , Set up thread tasks
  3. Create a Runnable Implementation class object of interface
  4. establish Thread Class object , Pass... In constructor Runnable Implementation class object of interface
  5. call Thread Class start Method , Start a new thread to execute run Method

The code case is as follows :

/** * 1. Create a Runnable Implementation class of interface  * @author zjq */
public class RunnableImpl implements Runnable{
    
    //2. Override... In the implementation class Runnable Interface run Method , Set up thread tasks 
    @Override
    public void run() {
    
        for (int i = 0; i <20 ; i++) {
    
            System.out.println(Thread.currentThread().getName()+"-->"+i);
        }
    }
}


public static void main(String[] args) {
    
    //3. Create a Runnable Implementation class object of interface 
    RunnableImpl run = new RunnableImpl();
    //4. establish Thread Class object , Pass... In constructor Runnable Implementation class object of interface 
    Thread t = new Thread(run);// Print thread name 
    //5. call Thread Class start Method , Start a new thread to execute run Method 
    t.start();

    for (int i = 0; i <20 ; i++) {
    
        System.out.println(Thread.currentThread().getName()+"-->"+i);
    }
}

Thread and Runnable The difference between

Realization Runnable Interface to create multithreaded programs :

  1. The limitation of single inheritance is avoided

A class can only inherit one class ( One can only have one father ), Class inherited Thread Class cannot inherit other classes .
Realized Runnable Interface , You can also inherit other classes , Implement other interfaces .

  1. Enhanced program scalability , Reduced program coupling ( decoupling )

Realization Runnable How to interface , The task of setting thread is separated from starting a new thread ( decoupling ).
In the implementation class , Rewrote run Method : Used to set thread tasks .
establish Thread Class object , call start Method : Used to start a new thread .

Start the thread with an anonymous inner class

Anonymous inner class start thread can simplify the coding of code .
The code case is as follows :

/**  Anonymous inner class way to create threads   anonymous : Isn't there a name   Inner class : Classes written inside other classes   Anonymous inner class functions : Simplify the code   To inherit a subclass from a parent , Overrides the method of the parent class , Create subclass objects in one step   Implement the class interface , Override methods in the interface , Create and implement class object composition in one step   The end product of anonymous inner classes : Subclass / Implementation class object , And this class has no name   Format : new  Parent class / Interface (){  Repeat parent class / Methods in interfaces  }; * @author zjq */
public class Demo01InnerClassThread {
    
    public static void main(String[] args) {
    
        // The parent class of the thread is Thread
        // new MyThread().start();
        new Thread(){
    
            // rewrite run Method , Set up thread tasks 
            @Override
            public void run() {
    
                for (int i = 0; i <20 ; i++) {
    
                    System.out.println(Thread.currentThread().getName()+"-->"+" Zhan ");
                }
            }
        }.start();

        // Thread interface Runnable
        //Runnable r = new RunnableImpl();// polymorphic 
        Runnable r = new Runnable(){
    
            // rewrite run Method , Set up thread tasks 
            @Override
            public void run() {
    
                for (int i = 0; i <20 ; i++) {
    
                    System.out.println(Thread.currentThread().getName()+"-->"+" Threads ");
                }
            }
        };
        new Thread(r).start();

        // The way to simplify the interface 
        new Thread(new Runnable(){
    
            // rewrite run Method , Set up thread tasks 
            @Override
            public void run() {
    
                for (int i = 0; i <20 ; i++) {
    
                    System.out.println(Thread.currentThread().getName()+"-->"+"zjq");
                }
            }
        }).start();
    }
}

版权声明
本文为[Have a drink together]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231544553342.html