Solve thread safety issues
The previous blog thread safety issue
1.synchronized keyword-monitor lock monitor lock
The bottom layer of synchronized is implemented using the mutex lock of the operating system .
- When the thread releases the lock, JMM will flush the shared variables in the working memory corresponding to the thread to the main memory;
- When a thread acquires a lock, JMM invalidates the local memory corresponding to the thread. As a result, the critical section code protected by the monitor must read shared variables from the main memory;
1. As a modifier of the method-before the definition of the method
synchronized int add(int a,int b){
...}
synchronized static int add(int a,int b){
...}
2. As a synchronous code block
synchronized(对象的引用){
......
}
3. Code demonstration
/**
* synchronized的语法使用示例
*/
public class ThreadDemo {
//同步方法
synchronized int add(int a,int b){
return 0;
}
synchronized static void sayHello(){
}
//同步代码块——能出现语句的地方
static void someMethod() {
Object object = new Object();
synchronized (object) {
}
}
}
2. Use synchronized to solve the thread safety problem of the code in the previous blog
public class ThreadDemo2 {
private static int n = 0;
private static final int COUNT = 100000;
static class Adder extends Thread{
@Override
public void run() {
for (int i = 0;i < COUNT;i++){
synchronized (Adder.class){
n++;
}
}
}
}
static class Suber extends Thread{
@Override
public void run() {
for (int i = 0;i < COUNT;i++){
synchronized (Adder.class){
//一定和上面的加同一把锁
n--;
}
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Adder();
Thread t2 = new Suber();
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(n);
}
}
3. volatile keyword
Modified shared variables can guarantee visibility and partly guarantee order ;
class ThreadDemo {
private volatile int n;
}