Multithreading (1) Introduction to Multithreading

1. Environment

  idea

2. Why use multithreading

As the saying goes: When people gather firewood, the flame is high. Why not let one person pick up firewood! ! ! Unity of course! ! But the most important thing is to improve efficiency

So the same is true in the program. You can talk about a thread as a person. In order to speed up the program efficiency, multithreading appears.

 3. What is a thread

Interview Question: What is the difference between a thread and a process

Answer: A thread is a way of running a program, and a process is a collection of threads

4. How to create a thread

For multi-threaded execution, we ignore the minimum error by default. The default is to execute at the same time. As for who executes first, it depends on who can strengthen the execution right of the CPU first.

4.1 Implement the Thread class

public class ThreadTest extends Thread {

    // Override the run method of the Thread type 
    @Override
     public  void run() {
        System.out.println( "The child thread runs -------" );
         // The logic code executed by the thread 
        for ( int i=0;i<20;i++ ){
            System.out.println(getName()+"i:"+i);
        }
        System.out.println( "Thread end" );
    }


}

Create test class

public static void main(String[] args) {
        ThreadTest threadTest = new ThreadTest(); // Create thread 
        threadTest.start(); // Start thread

        for(int i=0;i<20;i++){
            System.out.println(Thread.currentThread().getName() +"i:"+i); // The code that the main thread needs to run 
        }
    }

Why not use the thread.run() method to start multithreading: Since we create threads like ordinary new objects, using the run method is equivalent to calling methods, rather than starting multithreading

4.2 Inheriting the Runnable interface

public  class ThreadTest implements Runnable {
     // Rewrite the run method of Thread type

    public void run() {
        System.out.println( "The child thread runs -------" );
         // The logic code executed by the thread 
        for ( int i=0;i<20;i++ ){
            System.out.println(Thread.currentThread().getName()+"i:"+i);
        }
        System.out.println( "Thread end" );
    }


}

Create test class

 public static void main(String[] args) {
        ThreadTest threadTest=new ThreadTest();//创建线程
        Thread thread=new Thread(threadTest);
        thread.start(); // Start thread

        for(int i=0;i<20;i++){
            System.out.println(Thread.currentThread().getName() +"i:"+i); // The code that the main thread needs to run 
        }
    }

Comparing this method with the previous one, it can be seen that the two methods of creating threads are different

Interview question: Is it better to use the inherited Thred class or implement the Runnable interface to create a thread?

Answer: It is good to implement the Runnable interface, because Java only supports single inheritance, but supports multiple implementations

4.3 Use anonymous inner classes to create multithreading

 public static void main(String[] args) {
        Thread thread = new Thread( new Runnable() { // Anonymous inner class 
            public  void run() { // Business logic code 
                for ( int i=0;i<20;i++ ){
                    System.out.println(Thread.currentThread().getName()+"子线程i:"+i);
                }
            }
        });
        thread.start();
        for ( int i=0;i<20;i++){ // Main thread logic code 
            System.out.println(Thread.currentThread().getName()+"i:"+ i);
        }
    }

4.4 Common APIs for Multithreading

Common thread api methods

start()

start thread

currentThread()

Get the current thread object

getID()

Get the current thread ID Thread- number The number starts from 0 

getName()

Get the current thread name

sleep(long mill)

sleeping thread

Stop()

stop the thread,

Common thread constructor

Thread()

Allocate a new Thread  object

ThreadString name

Allocates a new Thread object with the specified name as its name .

ThreadRunable r

Allocate a new Thread object

ThreadRunable r, String name

Allocate a new Thread object

Five. Mutual conversion of several states of multi-threading

 

 

 

5.1 New state

   When a thread is created with the new operator, such as new Thread(r) , the thread has not yet started running, and the thread is in a new state. When a thread is in the nascent state, the program has not yet started running the code in the thread

5.2 Ready state

A newly created thread does not automatically start running. To execute the thread, the thread's start() method must be called. When the thread object calls the start() method, the thread is started. The start() method creates the system resources for the thread to run, and schedules the thread to run the run() method. When the start() method returns, the thread is in the ready state.

     The thread in the ready state does not necessarily run the run() method immediately, the thread must also compete with other threads for CPU time, and the thread can only be run if the CPU time is obtained. Because in a single- CPU computer system, it is impossible to run multiple threads at the same time, and only one thread is running at a time. So there may be multiple threads in the ready state at this point. Threads that are in the ready state are scheduled by the Java runtime system's thread scheduler .

5.3 Operational Status

When the thread gets CPU time, it enters the running state and actually starts to execute the run() method .

5.4 Blocking state

    During the running process of the thread, it may enter the blocking state for various reasons :
        1> The thread enters the sleep state by calling the sleep method;
        2> The thread calls an operation that is blocked on I/O , that is, the operation does not work until the input and output operations are completed. will return to its caller;
        3> the thread is trying to get a lock, and the lock is being held by another thread;
        4> the thread is waiting for a trigger condition;

5.5 State of death

There are two reasons why a thread dies:
  1) the run method exits normally and dies naturally,
   2) an uncaught exception terminates the run method and the thread dies suddenly.
  In order to determine whether the thread is currently alive (that is, it is either runnable or blocked), the isAlive method needs to be used. This method returns true if it is runnable or blocked ; if the thread is still new and not runnable, or if the thread dies, it returns false.

 

6. The role of join() method

To call the join() method of that thread is to execute the current thread when that thread is finished executing

E.g:

 

 public  static  void main(String[] args) {
         final Thread thread1= new Thread( new Runnable() { // Anonymous inner class 
            public  void run() { // Business logic code 
                for ( int i=0;i<20; i++ ){
                    System.out.println(Thread.currentThread().getName()+"子线程i:"+i);
                }
            }
        });
        Thread thread2 = new Thread( new Runnable() { // Anonymous inner class

            public  void run() { // business logic code 
                try {
                    thread1.join();
                } catch (InterruptedException e) {
                    e.printStackTrace ();
                }
                for (int i=0;i<20;i++){
                    System.out.println(Thread.currentThread().getName()+"子线程i:"+i);
                }
            }
        });
        thread2.start();
        thread1.start();


    }

 

Result: without thread1.join()

join thread1.join()

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325391422&siteId=291194637