当前位置:网站首页>Synchronized scope "concurrent programming"
Synchronized scope "concurrent programming"
2022-07-24 09:40:00 【liuyunshengsir】
stay Java in , have access to synchronized Keyword to mark a method or code block , When a thread calls synchronized Method or visit synchronized When a code block , This thread gets the lock of the object , This method is temporarily inaccessible to other threads , Only wait for this method to finish executing or code block to finish executing , This thread will release the lock of this object , Other threads can execute this method or code block .
It decorates the following objects :
Decorated code block , The decorated block of code is called the synchronized statement block , The scope of its action is curly braces {} Enclosed code , The object in action is the object that invokes the code block ;
Modification methods , The method being modified is called the synchronization method , Its scope is the entire method , The object in action is the object that calls the method ;
Modifying static methods , Its scope is the entire static method , The object is all the objects of the class ;
decorator , The scope of its function is synchronized The bracketed part of , The main object is all the objects of this class .
1 synchronized Method
1) When a thread is accessing an object synchronized Method , Then other threads cannot access other parts of the object synchronized Method . The reason is simple , Because an object has only one lock , When a thread acquires the lock on the object , Other threads cannot acquire the lock on this object , So the rest of the object cannot be accessed synchronized Method .
2) When a thread is accessing an object synchronized Method , Then other threads can access the object's non synchronized Method . The reason is simple , Visit non synchronized Method does not need to acquire the lock of the object , If one method doesn't work synchronized Keyword modification , Indicates that it will not use critical resources , So other threads can access this method ,
3) If a thread A Need to access object object1 Of synchronized Method fun1, Another thread B Need to access object object2 Of synchronized Method fun1, Even if object1 and object2 It's the same type ), It doesn't cause thread safety problems , Because they visit different objects , So there's no mutual exclusion .
public synchronized void run() {
for (int i = 0; i < 5; i ++) {
try {
System.out.println(Thread.currentThread().getName() + ":" + (count++));
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
synchronized Pay attention to the following points when decorating methods :
- (1)synchronized Keywords cannot inherit .
synchronized Not part of the method definition , therefore ,synchronized Keywords cannot be inherited . If a method in the parent class uses synchronized keyword , This method is covered in the subclass , This method in the subclass is not synchronized by default , You have to explicitly add synchronized Keywords are allowed .
(2) Cannot use... When defining interface methods synchronized keyword .
(3) The constructor cannot use synchronized keyword , But you can use synchronized Code block to synchronize
2 synchronized Synchronized block
synchronized Code block Than synchronized Method It's a little finer , It's also much more flexible to use . Because maybe only a part of the code in a method needs to be synchronized , If you use... For the whole method at this time synchronized To synchronize , It will affect the efficiency of program execution .
(1) A thread accesses... In an object synchronized(this) When synchronizing code blocks , Other threads trying to access the object will be blocked .
/**
* Synchronization thread
*/
class SyncThread implements Runnable {
private static int count;
public SyncThread() {
count = 0;
}
public void run() {
synchronized(this) {
for (int i = 0; i < 5; i++) {
try {
System.out.println(Thread.currentThread().getName() + ":" + (count++));
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public int getCount() {
return count;
}
}
SyncThread Call to :
SyncThread syncThread = new SyncThread();
Thread thread1 = new Thread(syncThread, "SyncThread1");
Thread thread2 = new Thread(syncThread, "SyncThread2");
thread1.start();
thread2.start();
give the result as follows :
SyncThread1:0
SyncThread1:1
SyncThread1:2
SyncThread1:3
SyncThread1:4
SyncThread2:5
SyncThread2:6
SyncThread2:7
SyncThread2:8
SyncThread2:9
(2)synchronized Just lock objects , There is only one lock per object (lock) Associated with it
Let's put SyncThread A little change in the call to :
Thread thread1 = new Thread(new SyncThread(), "SyncThread1");
Thread thread2 = new Thread(new SyncThread(), "SyncThread2");
thread1.start();
thread2.start();
give the result as follows :
SyncThread1:0
SyncThread2:1
SyncThread1:2
SyncThread2:3
SyncThread1:4
SyncThread2:5
SyncThread2:6
SyncThread1:7
SyncThread1:8
SyncThread2:9
Two are created SyncThread The object of syncThread1 and syncThread2, Threads thread1 Execution is syncThread1 Object synchronized Code (run), And threads thread2 Execution is syncThread2 Object synchronized Code (run); We know synchronized Locked objects , There will be two locks locked separately syncThread1 Objects and syncThread2 object , And these two locks don't interfere with each other , No mutual exclusion , So two threads can execute at the same time .
(3) When a thread accesses one of the objects synchronized(this) When synchronizing code blocks , Another thread can still access the non in the object synchronized(this) Synchronization code block .
class Counter implements Runnable{
private int count;
public Counter() {
count = 0;
}
public void countAdd() {
synchronized(this) {
for (int i = 0; i < 5; i ++) {
try {
System.out.println(Thread.currentThread().getName() + ":" + (count++));
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
// Not synchronized Code block , Not right count Read and write , So you don't have to synchronized
public void printCount() {
for (int i = 0; i < 5; i ++) {
try {
System.out.println(Thread.currentThread().getName() + " count:" + count);
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void run() {
String threadName = Thread.currentThread().getName();
if (threadName.equals("A")) {
countAdd();
} else if (threadName.equals("B")) {
printCount();
}
}
}
Calling code :
Counter counter = new Counter();
Thread thread1 = new Thread(counter, "A");
Thread thread2 = new Thread(counter, "B");
thread1.start();
thread2.start();
give the result as follows :
A:0
B count:1
A:1
B count:2
A:2
B count:3
A:3
B count:4
A:4
B count:5
In the above code countAdd It's a synchronized Of ,printCount Right and wrong synchronized Of . From the above results, we can see that a thread accesses an object synchronized When a code block , Other threads can access the object's non synchronized Blocks of code without blocking .
(4) Specifies to lock an object
/**
* Bank account
*/
class Account {
String name;
float amount;
public Account(String name, float amount) {
this.name = name;
this.amount = amount;
}
// Deposit money
public void deposit(float amt) {
amount += amt;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// Withdraw money
public void withdraw(float amt) {
amount -= amt;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public float getBalance() {
return amount;
}
}
/**
* Account operation class
*/
class AccountOperator implements Runnable{
private Account account;
public AccountOperator(Account account) {
this.account = account;
}
public void run() {
synchronized (account) {
account.deposit(500);
account.withdraw(500);
System.out.println(Thread.currentThread().getName() + ":" + account.getBalance());
}
}
}
Calling code :
Account account = new Account("zhang san", 10000.0f);
AccountOperator accountOperator = new AccountOperator(account);
final int THREAD_NUM = 5;
Thread threads[] = new Thread[THREAD_NUM];
for (int i = 0; i < THREAD_NUM; i ++) {
threads[i] = new Thread(accountOperator, "Thread" + i);
threads[i].start();
}
give the result as follows :
Thread3:10000.0
Thread2:10000.0
Thread1:10000.0
Thread4:10000.0
Thread0:10000.0
stay AccountOperator Class run In the method , use synchronized to account Object locking . When a thread accesses account Object time , Others try to visit account Object's thread will block , Until the thread accesses account End of object . That is to say, whoever gets the lock can run the code it controls .
When there is a specific object as a lock , You can write programs in a way like this .
public void method3(SomeObject obj){
//obj Locked objects
synchronized(obj){
// todo
}
}
When there is no explicit object as a lock , When you just want to synchronize a piece of code , You can create a special object to act as a lock :
class Test implements Runnable{
private byte[] lock = new byte[0]; // special instance Variable
public void method(){
synchronized(lock) {
// todo Synchronization code block
}
}
public void run() {
}
}
Zero length byte Array objects are more economical to create than any other object ―― Look at the compiled bytecode : Generate zero length byte[] The object only needs 3 Operation code , and Object lock = new Object() You need to 7 Line opcode .
3 synchronized Static methods
Static methods belong to classes, not objects . Again ,synchronized Decorated static methods lock all objects of this class .
/**
* Synchronization thread
*/
class SyncThread implements Runnable {
private static int count;
public SyncThread() {
count = 0;
}
public synchronized static void method() {
for (int i = 0; i < 5; i ++) {
try {
System.out.println(Thread.currentThread().getName() + ":" + (count++));
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public synchronized void run() {
method();
}
}
Calling code :
SyncThread syncThread1 = new SyncThread();
SyncThread syncThread2 = new SyncThread();
Thread thread1 = new Thread(syncThread1, "SyncThread1");
Thread thread2 = new Thread(syncThread2, "SyncThread2");
thread1.start();
thread2.start();
give the result as follows :
SyncThread1:0
SyncThread1:1
SyncThread1:2
SyncThread1:3
SyncThread1:4
SyncThread2:5
SyncThread2:6
SyncThread2:7
SyncThread2:8
SyncThread2:9
syncThread1 and syncThread2 yes SyncThread Two objects of , But in thread1 and thread2 Concurrent execution keeps threads synchronized .
4 synchronized class
Synchronized It can also act on a class , Usage is as follows :
class ClassName {
public void method() {
synchronized(ClassName.class) {
// todo
}
}
}
/**
* Synchronization thread
*/
class SyncThread implements Runnable {
private static int count;
public SyncThread() {
count = 0;
}
public static void method() {
synchronized(SyncThread.class) {
for (int i = 0; i < 5; i ++) {
try {
System.out.println(Thread.currentThread().getName() + ":" + (count++));
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public synchronized void run() {
method();
}
}
No matter what synchronized Keyword on method or object , If the object it works on is not static , The lock it acquires is the object ; If synchronized The object of action is a static method or a class , Then the lock it obtains is an object class , All objects of this class have the same lock .
5. summary
边栏推荐
- PHP Basics - PHP magic constants
- Learning transformer: overall architecture and Implementation
- Introduction to common ansible modules
- Getting started with identityserver4
- PHP Basics - PHP types
- ASI-20220222-Implicit PendingIntent
- Basic knowledge of PHP - complete collection of PHP functions
- Vim: use tags file to extend the automatic code completion function of YCM for the third-party library of C language
- Linux deployment mysql8.0
- Gin framework uses session and redis to realize distributed session & Gorm operation mysql
猜你喜欢
![[don't bother to strengthen learning] video notes (II) 1. What is Q-learning?](/img/4f/809adc96e30fad03a113acc3df4b61.png)
[don't bother to strengthen learning] video notes (II) 1. What is Q-learning?
![[don't bother with reinforcement learning] video notes (I) 3. Why use reinforcement learning?](/img/57/0ebff0839d2a2898472d3270fd13df.png)
[don't bother with reinforcement learning] video notes (I) 3. Why use reinforcement learning?

MySQL Basics (I) -- SQL Basics

One year after I came to Ali, I ushered in my first job change

Detailed explanation of the whole process of R & D demand splitting | agile practice
![[example of URDF exercise based on ROS] use of four wheeled robot and camera](/img/c5/babce5c6921b9cb54f018dc83a3b87.jpg)
[example of URDF exercise based on ROS] use of four wheeled robot and camera

Common evaluation indexes of medical image segmentation

代码随想录笔记_链表_25K个一组翻转链表
![[don't bother to strengthen learning] video notes (IV) 2. Dqn realizes maze walking](/img/53/5252c7c6989d142cc2ad6b1c6f513c.png)
[don't bother to strengthen learning] video notes (IV) 2. Dqn realizes maze walking

What if path is deleted by mistake when configuring system environment variables?
随机推荐
PHP debugging tool - socketlog installation and usage
Gin framework uses session and redis to realize distributed session & Gorm operation mysql
2022 trusted cloud authoritative assessment released: Tianyi cloud has obtained ten certifications and five best practices
SQL 优化原则
web安全入门-开源防火墙Pfsense安装配置
What is the component customization event we are talking about?
Scheme and software analysis of dual computer hot standby system "suggestions collection"
Gnuplot software learning notes
Spark Learning: how to choose different association forms and mechanisms?
Vim: use tags file to extend the automatic code completion function of YCM for the third-party library of C language
Detailed explanation of the whole process of R & D demand splitting | agile practice
With 8 years of product experience, I have summarized these practical experience of continuous and efficient research and development
Racecar multi-point navigation experiment based on ROS communication mechanism
[don't bother with reinforcement learning] video notes (I) 3. Why use reinforcement learning?
[don't bother to strengthen learning] video notes (IV) 1. What is dqn?
Ansible 常用模块介绍
【基于ROS的URDF练习实例】四轮机器人与摄像头的使用
JS locate Daquan to get the brother, parent and child elements of the node, including robot instances
[don't bother with reinforcement learning] video notes (I) 1. What is reinforcement learning?
程序的编译与链接