Java multithreading -- learning record

Learning content from“ Rookie tutorial ”And station B“ Meet the crazy God"

Thread, process, program

  • Process: a process includes memory space allocated by the operating system and contains one or more threads
  • Thread: it cannot exist independently. It must be part of a process
  • A thread refers to a single sequential flow of control in a process - what do you want to do with it
  • Multiple threads can be concurrent in a process, and each thread performs different tasks in parallel - that is, your grandfather gives orders and a group of grandchildren help you
  • Program: a program is an ordered collection of instructions, and a process is an execution of a program
  • The program is dead (static) and the process is live (dynamic)
  • Generally speaking, the procedure is permanent and the process is time bound

The necessity of multithreading

  • Improve the utilization of programs - to achieve more functions, like you squatting down the side of the pool while shaking the mouth, and the leek leaves may still be in tiktok at noon.
  • Reasonably allocate CPU resources - save your children from grabbing TV and toys (you play with toys first, you go to bed first, and you go...)

Possible disadvantages of multithreading

  • Initialization starts more slowly
  • Large and fast resource cost
  • The coding complexity may be higher - thread synchronization and locking
  • There may be interaction between threads - will the crash of one thread cause the problem of another thread
  • Security issues?

The life cycle of a thread

  • Inherit Thread class

  1. The custom Thread class inherits the Thread class

  2. Rewrite the run() method to write the thread execution body

  3. Create a thread object and call the start() method to start the thread
//Thread creation mode 1:
//1. Inherit Thread class - in order to make him do what,
//2. Rewrite the run() method -- what do you want it to do,
//3. Call start to start the thread --- what to do.

public class TestThread1 extends Thread{
    @Override
    public void run(){
        for (int i = 0; i < 6; i++) {
            System.out.println("I want to learn java Make a fortune!--"+i);
        }
    }
    public static void main(String[] args) {
        //main thread
        //Create a thread object
        TestThread1 testThread1 = new TestThread1();
        //Call the start() method to start the thread
        testThread1.start();
        for (int i = 0; i < 66; i++) {
            System.out.println("I'm learning to make a fortune--"+i);
        }
    }
}
  • Implement Runnable

  1. Define a class to implement the Runnable interface

  2. Implement the run() method and write the thread execution body

  3. Create a thread object and call the start() method to start the thread
//Create thread mode 2:
// Implement the runnble interface,
// Rewrite the run() method, and the execution thread needs to drop into the runnable interface class,
// Call the start() method
public class TestThread2 implements Runnable{
    @Override
    public void run(){
        for (int i = 0; i < 6; i++) {
            System.out.println("I'm learning java Make a lot of money--"+i);
        }
    }
    public static void main(String[] args) {
        //Create an implementation class object for the runnbale interface
        TestThread2 testThread2 = new TestThread2();
        //Create a thread object and start the thread agent through the thread object
        new Thread(testThread2).start();
        for (int j = 0; j < 66; j++) {
            System.out.println("I'm learning to make a lot of money--"+j);
        }
    }
}
  • Creating threads through Callable and Future

      1. Create the implementation class of the Callable interface and implement the call() method. The call() method will be used as the thread executor and has a return value.

      2. Create an instance of the Callable implementation class, and use the FutureTask class to wrap the Callable object, which encapsulates the return value of the call() method of the Callable object.

      3. Create and start a new Thread using the FutureTask object as the target of the Thread object.

      4. Call the get() method of the FutureTask object to get the return value after the execution of the child thread.

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class TestThread3 implements Callable<Integer> {

    //call method to implement callable
    @Override
    public Integer call() throws Exception {
        int i = 0;
        for (; i < 6; i++) {
            System.out.println("I'm learning java Make a lot of money--"+i);
        }
        //There is a return value
        return i;
    }

    public static void main(String[] args) {

        TestThread3 thread3 = new TestThread3();
        //Create and start a new Thread using the FutureTask object as the target of the Thread object.
        FutureTask<Integer> ft = new FutureTask<>(thread3);
        //Create a thread object and start the thread agent through the thread object
        new Thread(ft).start();

        for (int j = 0; j < 66; j++) {
            System.out.println("I'm learning to make a lot of money--"+j);
        }
        try {
            System.out.println("Child thread-Call Return value of method:" + ft.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}

The above three methods can achieve similar results.

Summary

It is recommended to implement the Runnable interface - reasons:

Compared with inheriting Thread class:
1) avoid the limitation caused by Java's single inheritance (you can only inherit a class once, can't you)
2) enhance the robustness of the program, the code can be shared by multiple threads, and the code and data are independent
3) the Thread pool can only put threads that implement Runable or Callable classes, not directly into classes that inherit threads
Compared with implementing Callable interface:
1) Runnable has been running since java1 1, and Callable was added after 1.5
2) the Callable interface supports the return of execution results, and futuretask needs to be called at this time The get () method is implemented. This method will block the main thread until the return result is obtained. When this method is not called, the main thread will not block

(I don't quite understand it. Take notes first and understand it slowly!)

Keywords: Java Multithreading

Added by immobilarity on Mon, 27 Dec 2021 21:06:39 +0200