One, atomic operation
1、ThreadLocal
Different threads operate the same ThreadLocal object to perform various operations without affecting the values in other threads
Note: Although ThreadLocal
useful, as a thread-level global variable, if some code depends on it, it will cause coupling, which affects the reusability of the code
2. The variable is declared as final
public class FinalDemo { private final int finalField; public FinalDemo ( int finalField) { this .finalField = finalField; } }
3. Lock
The code in the synchronous code block should be as short as possible. Do not add code that does not need synchronization to the synchronous code block. In the synchronous code block, do not perform operations that are particularly time-consuming or may block, such as I/O. operation or something.
A thread acquires a lock when it enters a certain 同步代码块
time, and releases the lock when it exits the code block
public class Increment { private int i; private Object lock = new Object(); public void increase(){ synchronized (lock){ i++; } } public int getI(){ synchronized (lock){ return i; } } public static void test(int threadNum,int loopTimes){ Increment increment = new Increment(); Thread[] threads = new Thread[threadNum]; for(int i = 0; i<threads.length;i++){ Thread t = new Thread(new Runnable() { @Override public void run() { for(int i = 0; i < loopTimes;i++){ increment.increase(); } } }); threads[i] = t; t.start(); } for (Thread t : threads) { // The main thread waits for other threads to finish executing try { t.join(); } catch (InterruptedException e) { throw new RuntimeException(e); } } System.out.println(threadNum + "threads, loop" + loopTimes + "results:" + increment.getI()); } public static void main(String[] args) { test(20, 1); test(20, 10); test(20, 100); test(20, 1000); test(20, 10000); test(20, 100000); } }
Reentrancy of two locks
As long as a thread holds a lock, it can enter any block of code protected by the lock.
ublic class SynchronizedDemo { private Object lock = new Object(); public void m1() { synchronized (lock) { System.out.println( "This is the first method" ); m2(); } } public void m2() { synchronized (lock) { System.out.println( "This is the second method" ); } } public static void main(String[] args) { SynchronizedDemo synchronizedDemo = new SynchronizedDemo(); synchronizedDemo.m1(); } }
Three, synchronization method
public class Increment { private int i; public void increase() { synchronized ( this ) { // use this as lock i++ ; } } public static void anotherStaticMethod() { synchronized (Increment. class ) { // Use the Class object as the lock // Fill in the code block that needs to be synchronized here } } }
Can be abbreviated as:
public class Increment { private int i; public synchronized increase() { // Use this as lock i++ ; } public synchronized static void anotherStaticMethod() { // Use the Class object as the lock // Fill in the code block that needs to be synchronized here } }