Multithreading implementation

Posted by sanand158 on Fri, 28 Jan 2022 23:20:30 +0100

Process and Thread

  • Speaking of process, we have to say procedure. Program is an ordered collection of instructions and data. It has no running meaning. It is a static concept.
  • The process is an execution process of the execution program, which is a dynamic concept. It is the unit of system resource allocation.
  • Usually, there can be several ready-made in a process. Of course, there is at least one ready-made in a process, otherwise there is no meaning of existence. Line city CPU scheduling and execution unit.

Note: many threads are simulated. Real multithreading refers to having multiple CPUs, which is often referred to as multi-core, such as server. If it is a simulated multithreading, that is, in the case of one CPU, the CPU can only execute one code at the same time point. Because the switching is fast, there is the illusion of simultaneous execution; Thread startup is not necessarily executed immediately, but is scheduled by the CPU

Core concept

  • Threads are independent execution paths;
  • When the program is running, it does not create its own thread in time, and there will be multiple threads in the background, such as main thread and gc thread (garbage collection thread)
  • main() is called the main thread, which is the entry of the system and is used to execute the whole program;
  • In a process, if multiple threads are opened up, the operation of threads is scheduled by the scheduler. The scheduler is closely related to the operating system, and the sequence can not be interfered by human beings.
  • When operating on the same resource, there will be the problem of resource grabbing, and concurrency control needs to be added;
  • Threads will bring additional overhead, such as cpu scheduling time and concurrency control overhead;
  • Each thread interacts in its own working memory. Improper memory control will lead to inconsistent data.

Three ways of thread implementation

Inherit Thread class

package com.example.thread;

/**
 * @author caoyu
 * TUDO:Thread creation method 1: inherit thread class
 * @version 1.0
 * @date 2021/6/17 10:24
 */
public class TestThread1 extends Thread{
    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            System.out.println("run Method thread-----"+i);
        }
    }

    /**
     * Main thread
     * @param args
     */
    public static void main(String[] args) {
        //Create thread object
        TestThread1 testThread1 = new TestThread1();
        //Call the start method to start the thread. Be careful not to call the run method. The following figure illustrates
        testThread1.start();
        for (int i = 0; i < 20; i++) {
            System.out.println("main Method thread---"+i);
        }
    }
}

Implement Runnable

Runnable objects are recommended because of the limitations of Java single inheritance

package com.example.thread;

/**
 * @author caoyu
 * TUDO:Thread creation mode 2: implement Runnable interface
 * @version 1.0
 * @date 2021/6/17 11:02
 */
public class CreateThread2 implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            System.out.println("run Method thread execution-----"+i);
        }
    }

    public static void main(String[] args) {
        //Create the implementation class object of runnable interface
        CreateThread2 createThread2 =  new CreateThread2();
        //Create a thread object and start our thread agent through the thread object
        new Thread(createThread2).start();
        for (int i = 0; i < 20; i++) {
            System.out.println("main Method thread execution---"+i);
        }
    }
}

Implement Callable interface

  1. To implement the Callable interface, the return value type is required
  2. When overriding the call method, you need to throw an exception
  3. Create target object
  4. Create execution service: executorservice ser = executors newFixedThreadPool(1);
  5. Submit execution: future result = Ser submit(1);
  6. Get result: Boolean B = result get();
  7. Shut down the service: Ser shutdownNow();
package com.example.thread;

import java.util.concurrent.*;

/**
 * @author caoyu
 * TUDO:Thread creation method: implement Callable interface
 * @version 1.0
 * @date 2021/6/17 13:58
 */
public class CreateThread3 implements Callable {

    @Override
    public Boolean call() throws Exception {
        for (int i = 0; i < 20; i++) {
            System.out.println("call Method thread--->"+i);
        }
        return true;
    }

    public static void main(String[] args) {
        CreateThread3 t1 = new CreateThread3();
        CreateThread3 t2 = new CreateThread3();
        CreateThread3 t3 = new CreateThread3();
        ExecutorService service = Executors.newFixedThreadPool(3);
        Future<Boolean> r1 = service.submit(t1);
        Future<Boolean> r2 = service.submit(t2);
        Future<Boolean> r3 = service.submit(t3);
        try {
            boolean b1 = r1.get();
            boolean b2 = r2.get();
            boolean b3 = r3.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }finally {
            service.shutdownNow();
        }
    }
}

advantage:

  • You can define the return value;
  • Exceptions can be thrown.

Supplement: why not call the run method

Comparison between Thread and Runnable

  • Inherit Thread class

    • The subclass inherits the Thread class and has the ability of multithreading
    • Start thread: subclass object start()
    • Not recommended: avoid the limitation of oop single inheritance
  • Implement Runnable interface

    • The implementation interface Runnable has multithreading capability
    • Start Thread: pass in the target object + Thread object start()
    • Recommended: it avoids the limitation of single inheritance, is flexible and convenient, and is convenient for the same object to be used by multiple threads
//A resource
StartThread s = new StartThread();
//Multiple agents
new Thread(s,"Xiao Hong").start();
new Thread(s,"Xiao Ming").start();
new Thread(s,"Xiao Gang").start();

Topics: Java Multithreading