Article directory
Preface
Contents of this chapter
`Shared issues, synchronized
1. Problems with sharing
- There is no problem with a program running multiple threads
- The problem lies in multiple thread access
共享资源
2.1 多个线程读`共享资源`其实也没有问题
2.2 在多个线程对`共享资源`读写操作时发生过指令交错,就会出现问题
共享资源
If there are pairs of multi-threaded read and write operations in a block of code , this block of code is called临界区
2. synchronized
语法:
synchronized(对象){
//临界区
}
Synchronized actually 对象锁
guarantees 临界区内代码的原子性
that the code in the critical section is indivisible to the outside world and will not be interrupted by thread switching.
2.1 synchronized object-oriented writing method
public class App {
public static void main(String[] args) throws Exception {
Room room = new Room();
Thread t1 = new Thread(() -> {
for (int i = 1; i <= 5000; i++) {
room.inc();
}
}, "t1");
Thread t2 = new Thread(() -> {
for (int i = 1; i <= 5000; i++) {
room.dec();
}
}, "t2");
t1.start();
t2.start();
t1.join();//等待t1线程执行完毕
t2.join();//等待t2线程执行完毕
System.out.println(room.getCount());
}
}
class Room {
private int count = 0;
public void inc() {
synchronized (this) {
count++;
}
}
public void dec() {
synchronized (this) {
count--;
}
}
public int getCount() {
synchronized (this) {
return count;
}
}
}
2.2 Synchronized on methods
成员方法上的写法
: What is locked is the current this object
class Room{
public synchronized void inc(){
//代码
}
}
等价于
class Room {
public void inc() {
synchronized (this) {
//代码
}
}
}
静态方法上的写法
: What is locked is the class object XXX.class
class Room {
public static synchronized void inc() {
//代码
}
}
等价于
class Room {
public static void inc(){
synchronized (Room.class){
//代码
}
}
}
Summarize
提示:这里对文章进行总结:
over