当前位置:网站首页>Leetcode 1116 print zero even odd (concurrent multithreading countdownlatch lock condition)
Leetcode 1116 print zero even odd (concurrent multithreading countdownlatch lock condition)
2022-06-11 01:44:00 【_ TCgogogo_】
You have a function printNumber that can be called with an integer parameter and prints it to the console.
- For example, calling
printNumber(7)prints7to the console.
You are given an instance of the class ZeroEvenOdd that has three functions: zero, even, and odd. The same instance of ZeroEvenOdd will be passed to three different threads:
- Thread A: calls
zero()that should only output0's. - Thread B: calls
even()that should only output even numbers. - Thread C: calls
odd()that should only output odd numbers.
Modify the given class to output the series "010203040506..." where the length of the series must be 2n.
Implement the ZeroEvenOdd class:
ZeroEvenOdd(int n)Initializes the object with the numbernthat represents the numbers that should be printed.void zero(printNumber)CallsprintNumberto output one zero.void even(printNumber)CallsprintNumberto output one even number.void odd(printNumber)CallsprintNumberto output one odd number.
Example 1:
Input: n = 2 Output: "0102" Explanation: There are three threads being fired asynchronously. One of them calls zero(), the other calls even(), and the last one calls odd(). "0102" is the correct output.
Example 2:
Input: n = 5 Output: "0102030405"
Constraints:
1 <= n <= 1000
Topic link :https://leetcode.com/problems/print-zero-even-odd/
The main idea of the topic : Initialize a ZeroEvenOdd example , The three threads hold and call their respective zero,odd,even Method , requirement zero Only the output 0,odd Only odd numbers are output ,even Only even numbers are output , Final output "010203040506..." This sequence
Topic analysis : There are many implementation methods , In this paper CountDownLatch + Lock + Condition The way ,CountDownLatch Used to ensure that when entering the cycle 0 First , The odd number is before, even after , After through condition Of await and signal Alternate operation , See notes for errors
8ms, Time beats 70.7%
public class ZeroEvenOdd {
ReentrantLock lock;
Condition cZero, cEven, cOdd;
// Used to ensure non-zero numbers start after zero
CountDownLatch zeroForOdd, zeroForEven;
int n;
public ZeroEvenOdd(int n) {
this.n = n;
lock = new ReentrantLock();
cZero = lock.newCondition();
cEven = lock.newCondition();
cOdd = lock.newCondition();
zeroForOdd = new CountDownLatch(1);
zeroForEven = new CountDownLatch(1);
}
public void zero(IntConsumer printNumber) throws InterruptedException {
lock.lock();
try {
for (int i = 1; i <= n; i ++) {
printNumber.accept(0);
if (i % 2 == 1) {
cOdd.signal();
} else {
cEven.signal();
}
if (i == 1) {
zeroForOdd.countDown();
}
// latch should be released to ensure even thread can end normally if n == 1
if (n == 1 || i == 2) {
zeroForEven.countDown();
}
cZero.await();
}
// **these "signal"s are important**
// when the last non-zero number accepted, corresponding thread will be in blocking state, which should be woken up to ensure it end normally.
cOdd.signal();
cEven.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void odd(IntConsumer printNumber) throws InterruptedException {
try {
zeroForOdd.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
lock.lock();
try {
for (int i = 1; i <= n; i += 2) {
printNumber.accept(i);
cZero.signal();
cOdd.await();
}
cZero.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void even(IntConsumer printNumber) throws InterruptedException {
try {
zeroForEven.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
lock.lock();
try {
for (int i = 2; i <= n; i += 2) {
printNumber.accept(i);
cZero.signal();
cEven.await();
}
// **this judgement is important**
// if lack of this judgement, odd can be blocked forever when n == 1:
// 1. [zero] get lock -> release two latches -> release lock -> blocked
// 2. [even] get lock -> release lock -> signal zero -> exit
// 3. [zero] get lock -> signal even and odd -> exit
// 4. [odd] get lock -> release lock -> blocked
if (n > 1) {
cZero.signal();
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}边栏推荐
- 立个flag--重构promise
- 2.0、ROS与PX4通信详解
- ava. Lang.noclassdeffounderror: org/apache/velocity/context/context solution
- 中间件_Redis_05_Redis的持久化
- 如何下载网页照片
- Leetcode 1574 shortest subarray to be removed to make array sorted
- SAS判别分析(Bayes准则和proc discrim过程)
- Tencent cloud database tdsql- a big guy talks about the past, present and future of basic software
- Leetcode search questions
- MATLAB数组其他常见操作笔记
猜你喜欢

Yunna PDA wireless fixed assets inventory management system

Projet Visualisation et analyse des données sur les épidémies basées sur le Web crawler

QGC ground station tutorial

How to write this with data and proc without SQL

Classic questions: 01 backpack, complete backpack, multiple backpack, two-dimensional cost Backpack

Once you know these treasure websites, you can't live without them!!!

Leetcode binary tree problem

Sealem finance builds Web3 decentralized financial platform infrastructure

2.0、ROS与PX4通信详解

SAS判别分析(Bayes准则和proc discrim过程)
随机推荐
Docking of express bird system
Function of barcode fixed assets management system, barcode management of fixed assets
Role of handlermethodargumentresolver + use case
Lazy singleton mode
2021-07-18 ROS笔记-基础和通讯
Linux安装mysql数据库详解
Makefile:1860: recipe for target ‘cmake_ check_ build_ system‘ failed make: *** [cmake_check_build_syst
Is the SQL query result different from what you expected? Mostly "null" is making trouble
threejs:如何获得几何体的boundingBox?
2.2. Ros+px4 simulation multi-point cruise flight - Square
1.4PX4程序下载
Introduction to the application process of China Patent Award, with a subsidy of 1million yuan
How to download web photos
Detailed explanation of classic papers on OCR character recognition
SAS主成分分析(求相关阵,特征值,单位特征向量,主成分表达式,贡献率和累计贡献率以及进行数据解释)
Introduction to the application process of Shenzhen China Patent Award, with a subsidy of 1million yuan
[recommended by Zhihu knowledge master] castle in UAV - focusing on the application of UAV in different technical fields
Leetcode 1605 find valid matrix given row and Column Sums
China-open-ssl编译的一些记录
SAS principal component analysis (finding correlation matrix, eigenvalue, unit eigenvector, principal component expression, contribution rate and cumulative contribution rate, and data interpretation)