当前位置:网站首页>Foundation of JUC concurrent programming (6) -- lock lock
Foundation of JUC concurrent programming (6) -- lock lock
2022-07-24 06:04:00 【aMythhhhh】
LOCK Interface
synchronized Keyword review
- Decorate a Synchronization statement code block , Scope is braces {} Enclosed code , The action object is the object that calls this code block .
- Decorate a Method , The method being modified is called the synchronization method , Its scope is the whole method , The object in action is the object that calls the method .
- Modify a static method .
- Decorate a class .
Multithreaded programming steps ( On )
Create a resource class , Define properties and operation methods ( The idea of high cohesion and low coupling )
Operate methods on resource classes
- Judge
- work
- notice
Create multiple threads , Call the operation method of the resource class
Examples of operation :
package com.amyth.JavaEE;
// Create a resource class
class Ticket{
private int number = 30;
// add synchronized Modification methods
public synchronized void sale(){
if(number > 0 ) {
System.out.println(Thread.currentThread().getName() + " sell 1 Tickets , The remaining :" + (number--) + " Zhang ");
}else{
System.out.println(Thread.currentThread().getName() + " sell 0 Tickets , The remaining :0 No tickets !!!");
}
}
}
public class SyncTest {
public static void main(String[] args) {
// Create resources
Ticket ticket = new Ticket();
new Thread(new Runnable() {
@Override
public void run() {
for (int i=0; i<30;i++)
{
ticket.sale();
}
}
},"AA").start();
new Thread(new Runnable() {
@Override
public void run() {
for (int i=0; i<40;i++)
{
ticket.sale();
}
}
},"BB").start();
new Thread(new Runnable() {
@Override
public void run() {
for (int i=0; i<40;i++)
{
ticket.sale();
}
}
},"CC").start();
}
}
Lock and Synchronized The difference between
Lock Locks achieve a wider range of lock operations than using synchronous methods and statements , More features .
- Lock No JAVA Built in ,Synchronized Is the key word , There are built-in features ,Lock Is a class , This class enables synchronous access .
- The big difference is this ,Lock The lock needs to be released manually , Otherwise, there may be “ Deadlock ” The phenomenon , and Synchronized Unwanted , It's automatic release .
utilize Reentrant lock :ReentrantLock Rewrite the above ticket selling case
package com.amyth.JavaEE;
import java.util.concurrent.locks.ReentrantLock;
// Create a resource class
class Ticket{
private int number = 100;
// Use reusable locks ReentrantLock
private final ReentrantLock lock = new ReentrantLock();
public void sale(){
lock.lock(); // locked
try{
if(number > 0 ) {
System.out.println(Thread.currentThread().getName() + " sell 1 Tickets , The remaining :" + (number--) + " Zhang ");
}else{
System.out.println(Thread.currentThread().getName() + " sell 0 Tickets , The remaining :0 No tickets !!!");
}
}finally {
lock.unlock(); // Unlock
}
}
}
public class SyncTest {
public static void main(String[] args) {
// Create resources
Ticket ticket = new Ticket();
// It's used here lambda Expressions simplify the code
// The interface implemented by anonymous class uses java.lang.FunctionalInterface annotation , And there is only one abstract interface method to be implemented
new Thread(() -> {
for (int i=0; i<30;i++)
{
ticket.sale();
}
},"AA").start();
new Thread(() -> {
for (int i=0; i<30;i++)
{
ticket.sale();
}
},"BB").start();
new Thread(() -> {
for (int i=0; i<30;i++)
{
ticket.sale();
}
},"CC").start();
}
}
- LOCK It can make the thread waiting for the lock respond to the interrupt ,synchronized no way , The waiting thread will wait forever .
- adopt LOCK You can know whether to acquire the lock , Keywords cannot do .
- LOCK It can improve the efficiency of reading operation by multiple threads .
in general , stay The competition for resources is fierce In the environment of ,LOCK The performance of is very, very good !
adopt synchronized Method for realizing interprocess communication number+1-1:
package com.amyth.JavaEE;
// Resource class creation
class Share{
private int number = 0;
public synchronized void incr() throws InterruptedException {
// Operation methods in resource classes
if(number!=0){
this.wait();
}
number++;
System.out.println("Thread number = "+number);
this.notify();
}
public synchronized void decr() throws InterruptedException {
if (number==0){
this.wait();
}
number--;
System.out.println("Thread number = "+number);
this.notify();
}
}
public class ThreadDemo1 {
public static void main(String[] args) {
Share share = new Share();
new Thread(()->{
for(int i =0;i<=10;i++){
try {
share.incr();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"ADD").start();
new Thread(()->{
for(int i =0;i<=10;i++){
try {
share.decr();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"Decr").start();
}
}
Examples of false wake-up problems : When the number of threads exceeds 2 After , Use if Judgment may lead to false awakening
package com.amyth.JavaEE;
// Resource class creation
class Share{
private int number = 0;
public synchronized void incr() throws InterruptedException {
// Operation methods in resource classes
if(number!=0){
this.wait();
}
number++;
System.out.println("Thread number = "+number);
this.notifyAll();
}
public synchronized void decr() throws InterruptedException {
if (number==0){
this.wait();
}
number--;
System.out.println("Thread number = "+number);
this.notifyAll();
}
}
public class ThreadDemo1 {
public static void main(String[] args) {
Share share = new Share();
new Thread(()->{
for(int i =0;i<=10;i++){
try {
share.incr();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"ADD").start();
new Thread(()->{
for(int i =0;i<=10;i++){
try {
share.decr();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"Decr").start();
new Thread(()->{
for(int i =0;i<=10;i++){
try {
share.incr();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"CC").start();
new Thread(()->{
for(int i =0;i<=10;i++){
try {
share.decr();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"DD").start();
}
}

At this point, the result appears 1、0 Other numbers , This is the false awakening situation .
make a concrete analysis :
AA Threads +1 after num=1 Wake up the rest of the threads
Maybe CC Grabbed the thread adopt if Judge num!=0 It's in wait
…
After a series of such operations , Once another thread wakes up CC Threads , At this point it will execute wait Later code
Because this is be based on wait The method wakes up wherever you fall asleep , therefore if Judgment only works once , The second time I was awakened, I didn't go through if
The solution is use while Cycle through judgment , When you wake up after sleeping, you will judge again in the cycle .
Use LOCK Lock implements the above example
package com.amyth.JavaEE;
import javax.naming.NameNotFoundException;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
// Create a resource class
class Numbers{
private int number=0;
private Lock lock= new ReentrantLock();
private Condition condition = lock.newCondition();
//+1
public void incr() throws InterruptedException {
lock.lock();
// Judge
try{
while(number !=0){
condition.await();
}
// work
number++;
System.out.println("number +1 :"+number);
// notice
condition.signalAll();
}finally {
lock.unlock();
}
}
//-1
public void decr() throws InterruptedException {
lock.lock();
// Judge
try{
while(number ==0){
condition.await();
}
// work
number--;
System.out.println("number -1 :"+number);
// notice
condition.signalAll();
}finally {
lock.unlock();
}
}
}
public class ThreadDemo2 {
public static void main(String[] args) {
Numbers numbers = new Numbers();
new Thread(() -> {
for (int i =0;i<=10;i++){
try {
numbers.incr();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"AA").start();
new Thread(() -> {
for (int i =0;i<=10;i++){
try {
numbers.decr();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"BB").start();
}
}
边栏推荐
- How to solve the problem of large distribution gap between training set and test set
- Learning rate optimization strategy
- 字符串方法以及实例
- JS star scoring effect
- Better CV link collection (dynamic update)
- 如何解决训练集和测试集的分布差距过大问题
- 【USB Host】STM32H7 CubeMX移植带FreeRTOS的USB Host读取U盘,USBH_Process_OS卡死问题,有个值为0xA5A5A5A5
- Conversion of world coordinate system, camera coordinate system and image coordinate system
- 【数据库系统原理】第四章 高级数据库模型:统一建模语言UML、对象定义语言ODL
- day4-jvm
猜你喜欢

Chapter 5 neural network

HAL_ Delay() delay error about 1ms

Jupyter notebook select CONDA environment

JVM系统学习

JUC并发编程基础(6)--Lock锁

MySQL基础---约束

"Statistical learning methods (2nd Edition)" Li Hang Chapter 15 singular value decomposition SVD mind map notes and after-school exercise answers (detailed steps) SVD matrix singular value Chapter 15

Qt新手入门级 计算器加、减、乘、除、应用

Jupyter notebook选择conda环境

JUC并发编程基础(8)--读写锁
随机推荐
Accessing a two-dimensional array with a pointer
头歌 平台作业
Points for attention in adding spp module to the network
JUC并发编程基础(7)--多线程锁
原生js放大镜效果
KMP代码分布详解
Iotp2pgate two IOT devices point-to-point communication fast implementation scheme
The problem that the user name and password are automatically filled in when Google / Firefox manages the background new account
Sequential stack C language stack entry and exit traversal
systemctl + journalctl
C语言链表(创建、遍历、释放、查找、删除、插入一个节点、排序,逆序)
DeepSort 总结
Write the list to txt and directly remove the comma in the middle
YOLOv5学习总结(持续更新)
[MYCAT] related concepts of MYCAT
Commands for quickly opening management tools
‘Results do not correspond to current coco set‘
systemctl + journalctl
Machine learning (zhouzhihua) Chapter 2 model selection and evaluation notes learning experience
[activiti] Introduction to activiti