- Background
Example: Creating a window to sell tickets, the total number of votes for the 100 that implement Runnable interface way
1. Problem: the process of selling tickets, there has been heavy vote, wrong vote -> there have been security problems thread
2. Causes of the problem: when a thread process of ticket operations, when completed, the operation has not been involved in other threads come in, also operates a ticket.
3. How to fix: When a thread a ticket at the time of the operation, other threads can not get involved. When a thread until the operation is complete ticket, other threads can start operation ticket. This occurred even thread a blocked and can not be changed.
- Java Solution: synchronization mechanisms
In Java, we passed synchronization mechanism to address security issues thread.
//方式一:同步代码块
synchronized(同步监视器){
//需要被同步的代码
}
Description:
- 1. The operation code of the shared data, the code that is to be synchronized. -> can not contain code for more, and can not contain less code.
-
2. Shared data: Variable multiple threads co-operation. For example: ticket is the sharing of data.
-
3. Synchronize monitor, commonly known as: lock. Any object of a class, can act as a lock.
要求:多个线程必须要共用同一把锁。
Added: In implement Runnable create multiple threads, we can consider this act as synchronization monitors.
Thread class inheritance to create multi-threaded mode, this acts as a synchronization monitors used with caution, given the current class act as synchronization monitors.
Second way: synchronization method
if the code sharing data in a full declaration operating method, we might as well declare this method synchronized.
About synchronization method Summary:
- Synchronization method still involves synchronizing the monitor, but we do not need to explicitly declare.
- Non-static method of synchronization is synchronization monitor: the this
static method of synchronization is synchronization monitor: the current class itself
Three ways: Lock Lock - JDK5.0 new
- Interview questions: synchronized and Lock of the similarities and differences?
- The same: both can solve thread safety issues
- Different: synchronized mechanisms been performed after the corresponding synchronization code, synchronization monitor automatically release
- Lock the need to manually start synchronization (lock (), at the same time also need to manually synchronize the end of implementation (unlock ())
Use of priority:
Lock -> sync block (has entered the body of the method of allocating the corresponding resource) -> synchronization method (Method outside the body)
-
Pros and cons of
a synchronized manner to solve the problem of security thread. - Benefits
Operation synchronization code, can only participate in one thread, other threads wait. The equivalent of a single-threaded process is inefficient. -
Interview questions: Java is how to solve thread safety issues, there are several ways? And compare different ways of
Contrast synchronized and Lock thread-safe way to solve the problem: face questions
Thread safe Singleton - lazy man
using a single synchronization mechanism in the embodiment mode rewritten lazy thread safe.
class Bank{
private Bank(){}
private static Bank instance = null;
public static Bank getInstance(){
//方式一:效率稍差
// synchronized (Bank.class) {
// if(instance == null){
//
// instance = new Bank();
// }
// return instance;
// }
//方式二:效率更高
if(instance == null){
synchronized (Bank.class) {
if(instance == null){
instance = new Bank();
}
}
}
return instance;
}
}
Interview questions: write a thread-safe singleton.
Hungry man style.
Lazy formula: provided above.
Deadlock
1. deadlock understand :
different threads are occupied by other resources required to synchronize not give up, are waiting for the other to give synchronization resources they need to form a thread deadlock
2. Description :
- 1 After the deadlock, does not appear abnormal, prompt does not appear, but the threads are in the blocked state can not continue
- 2 We use synchronization to avoid deadlock.
3. For example :
public static void main(String[] args) {
StringBuffer s1 = new StringBuffer();
StringBuffer s2 = new StringBuffer();
new Thread(){
@Override
public void run() {
synchronized (s1){
s1.append("a");
s2.append("1");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (s2){
s1.append("b");
s2.append("2");
System.out.println(s1);
System.out.println(s2);
}
}
}
}.start();
new Thread(new Runnable() {
@Override
public void run() {
synchronized (s2){
s1.append("c");
s2.append("3");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (s1){
s1.append("d");
s2.append("4");
System.out.println(s1);
System.out.println(s2);
}
}
}
}).start();
}