当前位置:网站首页>Example of reentrant lock thread waiting to wake up
Example of reentrant lock thread waiting to wake up
2022-04-23 06:09:00 【linsa_ pursuer】
1.synchronized
package juc.one;
/**
* First step Create a resource class , Define properties and operation methods
* The second step Judge work notice
* The third step Create multiple threads , Call the operation method of the resource class
* Step four Prevent false wake-up problems
*/
// First step Create a resource class , Define properties and operation methods
class Share {
// Initial value
private int number = 0;
//+1 Methods
public synchronized void incr() throws InterruptedException {
// The second step Judge work notice
while (number != 0){ // Judge number Is the value 0, If not 0, wait for
this.wait();// Prevent false awakening , To call in a loop
}
// If number The value is 0, Just +1 operation
number++;
System.out.println(Thread.currentThread().getName()+" :: "+number);
// Notify other threads
this.notifyAll();
}
//-1 Methods
public synchronized void decr() throws InterruptedException {
// Judge
while(number != 1){
this.wait();
}
// work
number--;
System.out.println(Thread.currentThread().getName()+" :: "+number);
// Notify other threads
this.notifyAll();
}
}
public class ThreadDemo1 {
// The third step Create multiple threads , Call the operation method of the resource class
public static void main(String[] args) {
Share share = new Share();
// Create thread
new Thread(()->{
for(int i = 1; i<=10; i++){
try {
share.incr();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"AA").start();
new Thread(()->{
for(int i = 1; i<=10; i++){
try {
share.decr();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"BB").start();
new Thread(()->{
for(int i = 1; i<=10; i++){
try {
share.incr();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"CC").start();
new Thread(()->{
for(int i = 1; i<=10; i++){
try {
share.decr();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"DD").start();
}
}
2.ReentrantLock
package juc.two;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class Share {
private int number = 0;
// establish lock
private Lock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
//+1
public void incr() throws InterruptedException {
// locked
lock.lock();
try {
// Judge
while (number != 0){
condition.await();
}
// work
number++;
System.out.println(Thread.currentThread().getName()+" :: "+number);
// notice
condition.signalAll();
}finally {
// Unlock
lock.unlock();
}
}
//-1
public void decr() throws InterruptedException {
lock.lock();
try{
// Judge
while (number != 1){
condition.await();
}
number--;
System.out.println(Thread.currentThread().getName()+" :: "+number);
condition.signalAll();
}finally {
lock.unlock();
}
}
}
public class ThreadDemo2 {
public static void main(String[] args) {
Share share = new Share();
// Create thread
new Thread(()->{
for(int i = 1; i<=10; i++){
try {
share.incr();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"AA").start();
new Thread(()->{
for(int i = 1; i<=10; i++){
try {
share.decr();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"BB").start();
new Thread(()->{
for(int i = 1; i<=10; i++){
try {
share.incr();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"CC").start();
new Thread(()->{
for(int i = 1; i<=10; i++){
try {
share.decr();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"DD").start();
}
}
版权声明
本文为[linsa_ pursuer]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204220533259406.html
边栏推荐
- Anaconda
- 常用编程记录——parser = argparse.ArgumentParser()
- Pyqy5 learning (2): qmainwindow + QWidget + qlabel
- Gaussian processes of sklearn
- Fundamentals of digital image processing (Gonzalez) II: gray transformation and spatial filtering
- Pyemd installation and simple use
- Implementation of displaying database pictures to browser tables based on thymeleaf
- Pytorch学习记录(三):神经网络的结构+使用Sequential、Module定义模型
- 线性代数第二章-矩阵及其运算
- 2. Average length of words
猜你喜欢
卡尔曼滤波与惯性组合导航
Pytorch学习记录(十二):学习率衰减+正则化
给yarn配置国内镜像加速器
String notes
图像恢复论文——[RED-Net, NIPS16]Image Restoration Using Very Deep Convolutional Encoder-Decoder Networks wi
Fundamentals of in-depth learning -- a simple understanding of meta learning (from Li Hongyi's course notes)
You cannot access this shared folder because your organization's security policy prevents unauthenticated guests from accessing it
Multithreading and high concurrency (1) -- basic knowledge of threads (implementation, common methods, state)
Create binary tree
Anaconda
随机推荐
Filebrowser realizes private network disk
Linear algebra Chapter 1 - determinant
Illustrate the significance of hashcode
SQL optimization best practices
Multithreading and high concurrency (3) -- synchronized principle
治疗TensorFlow后遗症——简单例子记录torch.utils.data.dataset.Dataset重写时的图片维度问题
数字图像处理基础(冈萨雷斯)一
IO multiplexing of 09 redis
String notes
Traitement des séquelles du flux de Tensor - exemple simple d'enregistrement de torche. Utils. Données. Dataset. Problème de dimension de l'image lors de la réécriture de l'ensemble de données
Code neat way to learn
In depth source code analysis servlet first program
EditorConfig
线代第四章-向量组的线性相关
Understanding and use of tp50, tp90 and tp99
Pytorch学习记录(十三):循环神经网络((Recurrent Neural Network)
Pytorch学习记录(十二):学习率衰减+正则化
卡尔曼滤波与惯性组合导航
Multithreading and high concurrency (1) -- basic knowledge of threads (implementation, common methods, state)
sklearn之 Gaussian Processes