Thread safety follows two aspects: atomicity and visibility (add personal understanding: consistency, main memory and consistency with thread memory) to start with an understanding of volatile and Synchronize
-
Use exit flags to allow the thread to exit normally, that is, to terminate when the run method completes.Copy the code
-
Using the stop method to forcibly terminate a thread (this method is not recommended because it can lead to unexpected results like suspend and resume) because stop releases locks and data consistency is not guaranteed.Copy the code
-
Interrupt a thread with the interrupt method.Copy the code
(1) The thread is blocked, such as using the sleep method. (2) Use while (! Interrupted ()) {… Throw new InterruptedException… } (Recommended method: Because exceptions can be thrown upwards, events can be propagated) (3) Combine InterruptedException with return (events cannot be propagated as with throw new InterruptedException)
Suspend: Why should resume be abandoned?
- If the synchronization method is used improperly, the synchronization method is exclusive and other threads cannot access it, resulting in deadlock.
- Threads are likely to pause, causing data to be out of sync.
Thread.suspend naturally causes deadlocks. If the target thread holds a lock on a monitor protecting a system-critical resource when it hangs, other threads cannot access the resource until the target thread recovers. If the thread that is restoring the target thread attempts to lock the monitor before calling resume, a deadlock occurs. This deadlock usually manifests itself as a “frozen” process.
GC is a daemon thread
Int num = 0 if multiple run methods call the add method outside the add method: not safe. If num = 0 is in the method, it is safe.
When num is set to get value, synchronize synchronize is used for all other threads to synchronize. See Concurrent Programming in Java, p. 65.
This one is also important. Read it carefully.
Synchronize lock reentry: You can retrieve your own internal lock again.
Synchronize code blocks synchronize code blocks synchronize code blocks
package com.sankuai.qcs.risk.web.service;
/ * *
- Description:
- @author: zhangleilei
- @date: 2018/2/5
* /
public class Test { public static void main(String[] args) { Add[] adder = new Add[10]; for (int i = 0; i < 10; i++) { adder[i] = new Add(); adder[i].start(); }}}
class Add extends Thread { volatile public static int count = 0;
synchronized public void add() { for (int i = 0; i < 10; i++) { count++; } System.out.println(“Thread:” + Thread.currentThread().getName() + “,Count:” + count); }
@Override
public void run() {
super.run();
add();
}
Copy the code
}
Thread:Thread-0,Count:10 Thread:Thread-1,Count:20 Thread:Thread-2,Count:30 Thread:Thread-3,Count:40 Thread:Thread-4,Count:50 Thread:Thread-5,Count:60 Thread:Thread-6,Count:70 Thread:Thread-7,Count:80 Thread:Thread-8,Count:90 Thread:Thread-9,Count:100