Java Novice Learning Guide [day15] --- Multithreading + Thread Safety

1. Thread

Thread in a computer: The smallest unit of application execution.

Process in computer: the smallest unit of computer scheduling and resource allocation

Thread in java: a task that needs to be executed in the program

The CPU scheduling resource in the computer is switched between various threads

Two ways to create threads:

1. Inherit the Thread class

Inherit the Thread class ----- "Rewrite the run method in the subclass ----- "Create a custom thread object ----- "Call the start method to start a new thread

2. Implement the Runnable interface

Create a Runnable implementation class ----- "Rewrite the run method in the implementation class ----- "Create an object of the implementation class ----- "Create an object of the Thread class, and use the object of the implementation class as a parameter at the same time Pass-----"Call the start method, start a new thread, and execute the task

The difference between run and start?

Run is just a normal method, calling the run method will not start a new thread.

start is a method provided in the Thread class, which will start a new thread, and jvm will automatically call the run method.

The five states of the thread: new ----- "ready -----" running ----- "blocking -----" death

2. Thread safety issues

The reason: multiple threads access a resource together, and the occurrence of data inconsistency is called a thread safety issue.

Solution: lock

1. Synchronized synchronization lock

Need a monitor object to ensure the uniqueness of the monitor object

synchronized(监听对象){
    
    
//可能出现线程安全的代码
}

note:

Synchronization code block

1. Monitoring this cannot satisfy uniqueness and achieve thread safety, because whoever calls this refers to whom

2. You can monitor bytecode files, for example: class name.class

3. Monitoring ordinary objects cannot guarantee thread safety, and static sharing needs to be added

4. It is possible to monitor string constants, but pay attention to the string constant pool

Synchronization method

1. Synchronization of ordinary methods is not possible, the reason is similar to monitoring this

2. Synchronous static method is available, similar to monitoring bytecode files

2, lock lock

//创建lock对象,多态方式
Lock lock = new ReentrantLock();
//上锁
lock.lock();
try{
    
    
    //可能出现线程安全的代码
    //加上try是为了保证不会编程死锁
}finally{
    
    
//解锁
    lock.unlock();
}

3. What is the difference between synchronized and Lock?

The same point: all are locked to ensure thread safety

difference:

Synchronized is at the jvm level, and the jvm is responsible for releasing locks and other issues, and the performance is low

Lock is a kind of lock proposed for concurrent access after jdk1.6, which is more flexible and efficient, but requires manual lock and release lock

Guess you like

Origin blog.csdn.net/WLK0423/article/details/109587379
Recommended