Multi-threaded basic study notes

Understand multithreading

Process and thread

A process is a program on a computer, and a thread is the execution unit in the
process. The process has many threads, heaps, and method areas, and the thread has its own stack, program counter, and local method stack.

Concurrency and parallelism

Concurrency: multiple tasks are executed at the
same time Parallel: multiple tasks are executed at the same time

Why use multithreading

Single processor: io operation and cpu operation cannot run at the same time, multi-threading can improve the efficiency of program operation
Multi-processor: using single thread can not use all cpu
servers at the same time: need to respond to multiple user requests at the same time

Problems to be dealt with when using multithreading

1, thread safety
2, deadlock
3, memory leak

Multi-threaded implementation

Inherit the Thread class

1. Construct a Thread subclass, rewrite the run method
2. Create an instance object of the subclass, and call the start method.
Features: Java can only inherit one parent class

Why not use the run method directly

Executing run can only run the code inside, and start can start a thread

Implement the Runnable interface

1. Construct the instance object of the Runnable interface subclass, rewrite the run method
2. Create the instance object of the subclass
3. Call the parameterized Thread construction method, call the start method
Features: Java can implement multiple interfaces, avoiding the limitations of single inheritance
Better handling of shared resources

Implement the Callable interface

1. Construct an instance object of the Callable interface subclass, rewrite the call method
2. Create an instance object of the subclass
3. Call the parameterized FutureTask construction method
4. Call the parameterized Thread construction method, call the start method
Features: return value, Declarable to throw an exception

Code:

public class Test2 {
    
    

	public static void main(String[] args) throws InterruptedException, ExecutionException {
    
    
		Thread1 t1 = new Thread1();
		t1.start();
		Thread2 t2 = new Thread2();
		new Thread(t2).start();
		Thread3 t3 = new Thread3();
		FutureTask<Object> f = new FutureTask<>(t3);
		Thread t = new Thread(f);
		t.start();
		System.out.println(f.get());
	}
}

class Thread1 extends Thread{
    
    
	public void run() {
    
    
		for(int i = 0; i < 10; i++) {
    
    
			System.out.println(Thread.currentThread().getName() + i);
		}
	}
}

class Thread2 implements Runnable{
    
    
	public void run() {
    
    
		for(int i = 0; i < 10; i++) {
    
    
			System.out.println(Thread.currentThread().getName() + i);
		}
	}
}

class Thread3 implements Callable<Object>{
    
    
	public Object call() throws Exception {
    
    
		// TODO Auto-generated method stub
		for(int i = 0; i < 10; i++) {
    
    
			System.out.println(Thread.currentThread().getName() + i);
		}
		return 10;
	}
}

Thread life cycle

New

When the object is created

Runnable

After calling the start method, it becomes operational. It
is divided into ready and running

block

Generally related
to locks. Blocking occurs while waiting to acquire locks
. It also occurs when IO requests are issued.

wait

Waiting occurs when using join, wait and other methods with no parameters. After
other threads use notify and notifyAll, the thread will be ready.

Timed waiting

Use sleep, wait, and join with parameters to wait regularly. After
other threads use notify and notifyAll, the thread
will enter the ready state. When the time is up , the thread will also enter the ready state.

death

Execution is completed, or an exception is thrown, the thread dies when the error occurs
, and it cannot enter other states after death

Thread scheduling

Preemptive scheduling: Strive for CPU resources according to priority.
Timing scheduling: Threads obtain time slices of the timing size and execute them

priority

High priority is easy to grab CPU resources,
priority is divided into 1 to 10
priority changes use setPriority method

concession

The thread enters the ready state and gives up cpu resources.
Use the yield method

Dormant

Use sleep method to make the thread sleep

Jump in line

A thread is inserted into B thread, only when A finishes running can B
use join method

Backstage

Threads are divided into foreground and background. By default, they are foreground.
Foreground threads are all over, and the program ends. You
need to use the setDeamon method before using the start method.

Multi-thread synchronization

Thread safe

When there is a delay, it will cause security problems, similar to the database

Synchronization code block

Use the synchronized method to lock an object, the following code block is synchronized

The object is arbitrary, but must be the same. The tag value is 1 when the code block is not executed, and 0 when it is used. When it is 0, other threads cannot execute the code block.

Synchronization method

Modified method with synchronized, the modified method is synchronized

The locked object when the method is locked is the object that called the method

Synchronous static method

No object is created, the lock of the synchronized static method is the class object of the method

Disadvantages of synchronized: each thread call needs to determine the value of the lock tag, which consumes a
lot of time. The thread needs to wait until the lock is obtained.

Sync lock

Use the Lock interface and ReentrantLock implementation class to construct a lock, and use the lock method and the unlock method to achieve thread synchronization.
Generally, the unlock method is written in finally

After the thread fails to apply for the lock multiple times, it no longer waits, which is more flexible

Multithreaded communication

The difference between wait and sleep:

The user of sleep is a thread, and the object used by wait is a synchronization lock object.
Wait abandons the lock object. Sleep does not give up
. The wait thread will not automatically wake up. You need notify and notifyAll. After the sleep method (and wait with parameters) is executed, the thread will automatically wake up.

The difference between notify and notifyAll

Notify wakes up the first waiting thread on the synchronization lock (the first thread that calls wait), notifyAll wakes up all waiting threads

Guess you like

Origin blog.csdn.net/sekever/article/details/114680283