Advanced java learning (thread based)
Keywords:
Java
I. thread safety
The concept of thread safety: when multiple threads access a class (object or method). This class always shows the correct behavior, so this class (object or method) is thread safe.
synchronized: you can lock any object or method, and the locked code is called "exclusive area" or "critical area"
Example: [com. Study. Base. Thread. A sync. Sync001] MyThread

package com.study.base.thread.a_sync.sync001;
/**
*
* Thread safety concept: when multiple threads access a class (object or method), the class can always show the correct behavior, then the class (object or method)
* It's thread safe
* synchronized:You can lock any object or method, and the locked code is called "exclusive area" or "critical area"
*
* Summary of examples
* When multiple threads access the run method of myThread, they are processed in the way of queuing (here the queuing is determined according to the order of CPU allocation),
* A thread wants to execute the code in the synchronized decorated method. First, it attempts to obtain the lock. If it obtains the lock, it executes the synchronized code body.
* If you can't get the lock, the thread will keep trying to get the lock until you get it, and multiple threads will compete for the lock at the same time (that is, there will be a problem of lock competition).
*/
public class MyThread implements Runnable {
private int count = 5;
//synchronized Lock up
public synchronized void run() {
count--;
System.out.println(Thread.currentThread().getName()+" count = "+count);
}
public static void main(String[] args) {
/**
* Analysis:
* When multiple threads access the run method of myThread, they are processed in the way of queuing (here, the queuing is determined according to the order of cpu allocation)
* 1 Try to get lock
* 2 If you get the lock, execute the synchronized code body content: if you can't get the lock, the thread will keep trying to get the lock until you get it
* And multiple threads compete for the lock at the same time, that is to say, there will be lock competition
*/
MyThread mythread = new MyThread();
Thread t1 = new Thread(mythread,"t1");
Thread t2 = new Thread(mythread,"t2");
Thread t3 = new Thread(mythread,"t3");
Thread t4 = new Thread(mythread,"t4");
Thread t5 = new Thread(mythread,"t5");
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
}
}
MyThread
Summary of examples
When multiple threads access the run method of myThread, they are queued (here, the queuing is determined according to the order of CPU allocation). If a thread wants to execute the code in the synchronized decorated method, it first attempts to obtain the lock. If it obtains the lock, it executes the synchronized code content. If it cannot obtain the lock, it will try to obtain the lock continuously Put the lock until you get it, and multiple threads compete for the lock at the same time (that is, there will be a lock competition problem).
2. Multiple threads and locks
Multiple threads and multiple locks: multiple threads, each thread can get the lock specified by itself, obtain the lock respectively, and then execute the content of synchronized method body
Example: [com. Study. Base. Thread. A sync. Sync002] MultiThread

package com.study.base.thread.a_sync.sync002;
/**
* Multiple threads and multiple locks: multiple threads, each thread can get the lock specified by itself, obtain the lock respectively, and then execute the content of synchronized method body
* The locks obtained by the keyword synchronized are all object locks, rather than taking a piece of code (method) as locks. Therefore, in the example code, which thread executes the method of synchronized keyword first, and which thread holds the Lock of the object to which the method belongs, two objects. What the thread gets is two different locks, they don't affect each other
* One case is the same lock, even if the synchronized keyword is added to the static method to lock the. Class, class level lock (exclusive. Class class)
*/
public class MultiThread {
private int num = 0;
public synchronized void printNum(String tag) {
try {
if(tag.equals("a")) {
num = 100;
System.out.println("tag a , set num over");
Thread.sleep(1000);
} else {
num = 200 ;
System.out.println("tag b , set num over");
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("tag "+tag+" , num = "+num);
}
//Observe and observe run Method output order
public static void main(String[] args) {
//Two different objects
final MultiThread m1 = new MultiThread();
final MultiThread m2 = new MultiThread();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
m1.printNum("a");
}
},"t1");
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
m2.printNum("b");
}
},"t2");
t1.start();
t2.start();
}
}
MultiThread
Summary of examples
The Lock obtained by the keyword synchronized is an object Lock, rather than a piece of code (method) as a Lock, so in the example code, which thread executes the method of synchronized keyword first, and which thread holds the Lock of the object to which the method belongs, two objects. Threads get two different locks. They don't affect each other. One case is the same Lock. Even if the synchronized keyword is added to the static method, it means Lock at the level of. Class and class (exclusive. Class)
3. Synchronization and asynchrony of object lock
Synchronization: the concept of synchronized synchronization is sharing. We should firmly remember the word "sharing". If it is not a shared resource, there is no need to synchronize
Asynchronized: the concept of asynchronized asynchronism is independence, without any restriction on each other. It's like when we learn http, we can continue to browse and operate the content of the page in the Ajax request initiated by the page. There is no relationship between the two
The purpose of synchronization is for thread safety. In fact, for thread safety, two features need to be met:
Atomicity (synchronization)
Visibility
Example: [com. Study. Base. Thread. A sync. Sync003] MyObject

package com.study.base.thread.a_sync.sync003;
/**
*
* Synchronization and asynchrony of objects
*
*/
public class MyObject {
public synchronized void method1() {
try {
System.out.print(Thread.currentThread().getName());
Thread.sleep(4000);
} catch (Exception e) {
e.printStackTrace();
}
}
/** synchronized */
public void method2() {
System.out.println(Thread.currentThread().getName());
}
public static void main(String[] args) {
final MyObject mo = new MyObject();
/**
* Analysis:
* t1 The thread first holds the lock lock of the object object, and the t2 thread can call the non synchronized decorated methods in the object asynchronously
* t1 The thread first holds the lock lock of the object object. If t2 thread calls the synchronized method in the object at this time, it needs to wait, that is, synchronization
*/
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
mo.method1();
}
},"t1");
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
mo.method2();
}
},"t2");
t1.start();
t2.start();
}
}
MyObject
Thread A first holds the Lock lock of the object object. If thread B calls the synchronized method of the object at this time, it needs to wait, that is, synchronization
Thread A holds the Lock lock of the object first, and thread B can call the non synchronized decorated methods in the object asynchronously
For synchronous and asynchronous methods of objects, when designing our own programs, we must consider the whole problem, or there will be data inconsistency errors. The classic error is dirty read
Example: [com. Study. Base. Thread. A sync. Sync004] DirtyRead
When we lock the methods of an object, we need to consider the integrity of the business, that is, the setValue / getValue methods lock the synchronized keywords at the same time, to ensure the atomicity of the business (service), otherwise there will be business errors (also to ensure the consistency of the business from the side).