Knowledge points about multithreading learning (super detailed)

About multithreading learning

What is thread synchronization

Thread synchronization means that when a thread is operating on memory, other threads cannot operate on the memory address until the thread completes the operation and other threads are in a waiting state.

The Thread class implements multithreading

  • Inherit extend Thread custom Thread class
  • Rewrite the run method and write the thread execution body
  • Create a thread object and call the start method to start the thread
  • Call the start method to execute two threads at the same time
  • Thread startup is not necessarily executed immediately, but is scheduled by cpu

The Runable interface implements multithreading (most used)

  1. The instance class inherits the interface through implements
  2. Override the run method in the class (ctrl+o, alt+fn+ins)
  3. Create the object of this class through new thread(). start(); start-up

The Callable interface uses the least

Functional interface

An interface contains only one abstract method.

alt +enter create method.

Thread stop

It is recommended to use the flag bit to stop the thread and set a method

Call testStop.stop(); Cut in line

Thread sleep

Call Thread.sleep(); Achieve sleep

Thread comity

Comity thread, which stops the currently executing thread without blocking

Transition a thread from a running state to a ready state

Let CPU scheduling, comity is not necessarily successful. Look at your mood

Add Thread.yield() to the thread method;

Thread enforcement

Thread.join();

Observe thread status

Thread.getState();

thread priority

Thread. getPriority() get priority thread. setPriority(); set priority

Daemon thread

Threads are divided into user threads and daemon threads

The virtual machine must ensure that the user thread is completed

The virtual machine does not have to wait for the daemon thread to finish executing

Case: record the operation log in the background and monitor the memory

thread.setDaemon(true) / / the default value is false, indicating that the user thread and normal threads are user threads

When the user thread stops, the daemon thread will execute for some time

Thread synchronization mechanism

Multiple threads operate on the same resource

Concurrency: the same object is operated by multiple threads at the same time

Locking mechanism

Each object has a lock. sleep does not release the lock

Add synchronized at the corresponding method

Defect: declaring a large method synchronized will affect efficiency

Write the amount of change into the synchronized () code block

Synchronization block: synchronized (obj) {}

obj is called synchronization monitor

obj can be any object, but shared resources are recommended as synchronization monitors

There is no need to specify a synchronization monitor in the synchronization method,

copyonwritearraylist

This is a secure object

Conditions for deadlock generation

  1. Mutex condition a resource can only be used by one process at a time
  2. Request and hold condition a process is blocked by a request for resources and holds on to the resources obtained
  3. The resources obtained by the process cannot be forcibly deprived until they are used up

Lock lock

The java.util.concurrent.locks.Lock interface is a tool that controls multiple threads to access shared resources

Locks provide exclusive access to shared resources. Only one thread can Lock the Lock object at a time. Threads should obtain the Lock object before accessing shared resources

RenntrantLock class implements Lock. It has the same concurrency and memory semantics as synchronized. ReentrantLock is commonly used in thread safety control. It can display locking and release locks.

class A{
private final ReentrantLock lock = new ReenTrantLock();
public void m(){
lock.lock();
try{
1/Thread safe code;
}
finally{
lock.unlock);
1/If the synchronization code is abnormal, you should unlock()write in finally Statement block
}
}
}

synchronized vs Lock

  1. Lock is a display lock (manually open and close, don't forget to close the lock). synchronized is an implicit lock, which is automatically released when it is out of the scope
  2. Lock only has code block lock, and synchronized has code block lock and method lock
  3. Using Lock locks, the jvm will spend less time scheduling threads and perform better. And it has better scalability
  4. Priority order

Lock code block synchronization method

Pipe program method

this.wait();Thread waiting
this.notifyAll();Wake up thread
public class jjj {
    public static void main(String[] args) {
        SynContainer synContainer=new SynContainer();
        new Productor(synContainer).start();
        new Consumer(synContainer).start();
    }
}
//producer

class  Productor extends Thread{
SynContainer container;
    public Productor(SynContainer container) {
        this.container = container;
    }
    //production

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            container.push(new Chicken(i));
            System.out.println("Produced"+i+"Chicken");
        }
    }
}
//consumer
class Consumer extends Thread{
    SynContainer container;
    public Consumer(SynContainer container) {
        this.container = container;
    }
    //consumption
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("Consumption——>"+container.pop().id+"Chicken");
        }
    }
}
//product
class Chicken{
    int id;

    public Chicken(int id) {
        this.id = id;
    }
}
//buffer
class SynContainer{
    //A container size is required
    Chicken[]chickens=new Chicken[10];
    int count=0;
    //The producer puts in the product
public synchronized void push(Chicken chicken){
    //If the container is full, you need to wait for consumption
    if(count==chickens.length){
        //Inform consumers to consume and producers to wait
        try {
            this.wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    //If it is not full, we need to throw in the product
    chickens[count]=chicken;
    count++;
    //Inform consumers of consumption
    this.notifyAll();
}


    //Consumer products
public synchronized Chicken pop(){
    //Judge whether it can be consumed
    if (count==0)
    {
        //Wait for producers to produce, consumers to wait
        try {
            this.wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    //If you can consume
    count--;
    Chicken chicken=chickens[count];
//When finished, inform the producer to produce
    this.notifyAll();
    return chicken;
}

}

Thread pool

  1. ExecutorService: the real thread pool interface, a common subclass ThreadPoolExecutor
  2. void execute(Runnable command): executes a task without a return value. It is generally used to execute Runnable
  3. void shutdown(); Close thread pool
  4. Executors; Tool class, the factory class of thread pool, which is used to create and return different types of thread pools
import java.util.EmptyStackException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Test {
    public static void main(String[] args) {
//1. Create service and thread pool
        //The newFixedThreadPool parameter is; Thread pool size
        ExecutorService service= Executors.newFixedThreadPool(10);
        //implement
        service.execute(new MyThread());
        service.execute(new MyThread());
        service.execute(new MyThread());
        service.execute(new MyThread());
        //Close link
        service.shutdown();
    }
}





class MyThread implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName());
    }

summary

import jdk.nashorn.internal.codegen.CompilerConstants;

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

public class Test1 {
    public static void main(String[] args) {
        new MyThread1().start();
        new Thread(new MyThread2()).start();
        FutureTask<Integer>futureTask=new FutureTask<Integer>(new MyThread3());
        new Thread(futureTask).start();
        try {
            Integer integer = futureTask.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}
//Inherit Thread class
class MyThread1 extends Thread{
    @Override
    public void run() {
        System.out.println("MyThread1");
    }
}
//Implement Runnable interface
class MyThread2 implements Runnable{

    @Override
    public void run() {
        System.out.println("MyThread2");
    }
}
//Implement Callable interface
class MyThread3 implements Callable<Integer>{

    @Override
    public Integer call() throws Exception {
        System.out.println("MyThread3");
        return 100;
    }
}

Posted by davex on Sun, 24 Oct 2021 02:52:30 -0700