[知识总结] 【leetcode】多线程编程题题解
作者:CC下载站 日期:2021-11-15 03:53:00 浏览:60 分类:编程开发
本文将记录力扣多线程下的题目:
每道题基本都有很多种解法,基本都可以使用变量
、Semaphore
、CountDownLatch
等手段来控制。
1114.按序打印
1.变量控制
class Foo {
private volatile int flag = 1;
public Foo() {}
public void first(Runnable printFirst) throws InterruptedException {
// printSecond.run() outputs "first". Do not change or remove this line.
printFirst.run();
flag = 2;
}
public void second(Runnable printSecond) throws InterruptedException {
while (flag != 2);
// printSecond.run() outputs "second". Do not change or remove this line.
printSecond.run();
flag = 3;
}
public void third(Runnable printThird) throws InterruptedException {
while (flag != 3);
// printThird.run() outputs "third". Do not change or remove this line.
printThird.run();
}
}
2.Semaphore
class Foo {
public Semaphore seam_first_two = new Semaphore(0);
public Semaphore seam_two_second = new Semaphore(0);
public Foo() {}
public void first(Runnable printFirst) throws InterruptedException {
// printSecond.run() outputs "first". Do not change or remove this line.
printFirst.run();
seam_first_two.release();
}
public void second(Runnable printSecond) throws InterruptedException {
seam_first_two.acquire();
// printSecond.run() outputs "second". Do not change or remove this line.
printSecond.run();
seam_two_second.release();
}
public void third(Runnable printThird) throws InterruptedException {
seam_two_second.acquire();
// printThird.run() outputs "third". Do not change or remove this line.
printThird.run();
}
}
3.CountDownLatch
class Foo {
private CountDownLatch second = new CountDownLatch(1);
private CountDownLatch third = new CountDownLatch(1);
public Foo() {}
public void first(Runnable printFirst) throws InterruptedException {
// printSecond.run() outputs "first". Do not change or remove this line.
printFirst.run();
second.countDown();
}
public void second(Runnable printSecond) throws InterruptedException {
second.await();
// printSecond.run() outputs "second". Do not change or remove this line.
printSecond.run();
third.countDown();
}
public void third(Runnable printThird) throws InterruptedException {
third.await();
// printThird.run() outputs "third". Do not change or remove this line.
printThird.run();
}
}
4.AtomicInteger
class Foo {
private AtomicInteger firstJobDone = new AtomicInteger(0);
private AtomicInteger secondJobDone = new AtomicInteger(0);
public Foo() {}
public void first(Runnable printFirst) throws InterruptedException {
// printFirst.run() outputs "first".
printFirst.run();
// mark the first job as done, by increasing its count.
firstJobDone.incrementAndGet();
}
public void second(Runnable printSecond) throws InterruptedException {
while (firstJobDone.get() != 1) {
// waiting for the first job to be done.
}
// printSecond.run() outputs "second".
printSecond.run();
// mark the second as done, by increasing its count.
secondJobDone.incrementAndGet();
}
public void third(Runnable printThird) throws InterruptedException {
while (secondJobDone.get() != 1) {
// waiting for the second job to be done.
}
// printThird.run() outputs "third".
printThird.run();
}
}
1115.交替打印FooBar
1.Semaphore
class FooBar {
private int n;
public Semaphore semaphoreFoo = new Semaphore(1);
public Semaphore semaphoreBar = new Semaphore(0);
public FooBar(int n) {
this.n = n;
}
public void foo(Runnable printFoo) throws InterruptedException {
for (int i = 0; i < n; i++) {
semaphoreBar.acquire();
// printFoo.run() outputs "foo". Do not change or remove this line.
printFoo.run();
semaphoreBar.release();
}
}
public void bar(Runnable printBar) throws InterruptedException {
for (int i = 0; i < n; i++) {
semaphoreBar.acquire();
// printBar.run() outputs "bar". Do not change or remove this line.
printBar.run();
semaphoreFoo.release();
}
}
}
2.CyclicBarrier
class FooBar {
private int n;
private CyclicBarrier cb = new CyclicBarrier(2);
private volatile boolean fooExec = true;
public FooBar(int n) {
this.n = n;
}
public void foo(Runnable printFoo) throws InterruptedException {
for (int i = 0; i < n; i++) {
while (!fooExec) {
//false的时候,bar线程在执行,foo线程在这此处空转
}
printFoo.run();//打印foo
fooExec = false;//设置变量
try {
cb.await();//线程foo到达同步点
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}
}
public void bar(Runnable printBar) throws InterruptedException {
for (int i = 0; i < n; i++) {
try {
cb.await();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
printBar.run();
fooExec = true;
}
}
}
3.Thread.yield()
class FooBar {
private int n;
private volatile boolean fooExec = true;
public FooBar(int n) {
this.n = n;
}
public void foo(Runnable printFoo) throws InterruptedException {
for (int i = 0; i < n;) {
if (fooExec) {
printFoo.run();
fooExec = false;
i++;
} else {
Thread.yield();
}
}
}
public void bar(Runnable printBar) throws InterruptedException {
for (int i = 0; i < n;) {
if (!fooExec) {
printBar.run();
fooExec = true;
i++;
} else {
Thread.yield();
}
}
}
}
4.BlockingQueue
class FooBar {
private int n;
private BlockingQueue<Integer> fooQueue = new LinkedBlockingQueue<Integer>() {{
add(0);
}};
private BlockingQueue<Integer> barQueue = new LinkedBlockingQueue<>();
public FooBar(int n) {
this.n = n;
}
public void foo(Runnable printFoo) throws InterruptedException {
for (int i = 0; i < n; i++) {
fooQueue.take();
printFoo.run();
barQueue.add(0);
}
}
public void bar(Runnable printBar) throws InterruptedException {
for (int i = 0; i < n; i++) {
barQueue.take();
printBar.run();
fooQueue.add(0);
}
}
}
1116.打印零与奇偶数
1.Semaphore
class ZeroEvenOdd {
private int n;
private Semaphore zeroSema = new Semaphore(1);
private Semaphore oddSema = new Semaphore(0);
private Semaphore evenSema = new Semaphore(0);
public ZeroEvenOdd(int n) {
this.n = n;
}
// printNumber.accept(x) outputs "x", where x is an integer.
public void zero(IntConsumer printNumber) throws InterruptedException {
for (int i = 1; i <= n; i++) {
zeroSema.acquire();
printNumber.accept(0);
if (i % 2 == 1) {
oddSema.release();
} else {
evenSema.release();
}
}
}
public void even(IntConsumer printNumber) throws InterruptedException {
for (int i = 1; i <= n; i++) {
if (i % 2 == 0) {
evenSema.acquire();
printNumber.accept(i);
zeroSema.release();
}
}
}
public void odd(IntConsumer printNumber) throws InterruptedException {
for (int i = 1; i <= n; i++) {
if (i % 2 == 1) {
oddSema.acquire();
printNumber.accept(i);
zeroSema.release();
}
}
}
}
2.CountDownLatch
class ZeroEvenOdd {
private int n;
private CountDownLatch zeroLatch = new CountDownLatch(0);
private CountDownLatch evenLatch = new CountDownLatch(1);//偶数
private CountDownLatch oddLatch = new CountDownLatch(1);//奇数
public ZeroEvenOdd(int n) {
this.n = n;
}
public void zero(IntConsumer printNumber) throws InterruptedException {
for (int i = 1; i <= n; i++) {
zeroLatch.await();
printNumber.accept(0);
zeroLatch = new CountDownLatch(1);
if (i % 2 == 1) {
oddLatch.countDown();
} else {
evenLatch.countDown();
}
}
}
public void even(IntConsumer printNumber) throws InterruptedException {
for (int i = 1; i <= n; i++) {
if (i % 2 == 0) {
evenLatch.await();
printNumber.accept(i);
evenLatch = new CountDownLatch(1);
zeroLatch.countDown();
}
}
}
public void odd(IntConsumer printNumber) throws InterruptedException {
for (int i = 1; i <= n; i++) {
if (i % 2 == 1) {
oddLatch.await();
printNumber.accept(i);
oddLatch = new CountDownLatch(1);
zeroLatch.countDown();
}
}
}
}
3.AtomicInteger+Thread.yield()
class ZeroEvenOdd {
private int n;
private AtomicInteger ai = new AtomicInteger(0);
public ZeroEvenOdd(int n) {
this.n = n;
}
public void zero(IntConsumer printNumber) throws InterruptedException {
for (int i = 0; i < n; i++) {
while (ai.get() != 0 && ai.get() != 2) {
Thread.yield();
}
printNumber.accept(0);
ai.incrementAndGet();
}
}
public void even(IntConsumer printNumber) throws InterruptedException {
for (int i = 2; i <= n; i += 2) {
while (ai.get() != 3) {
Thread.yield();
}
printNumber.accept(i);
ai.set(0);
}
}
public void odd(IntConsumer printNumber) throws InterruptedException {
for (int i = 1; i <= n; i += 2) {
while (ai.get() != 1) {
Thread.yield();
}
printNumber.accept(i);
ai.set(2);
}
}
}
4.变量+Thread.yield()
class ZeroEvenOdd {
private int n;
private volatile int state;
public ZeroEvenOdd(int n) {
this.n = n;
}
public void zero(IntConsumer printNumber) throws InterruptedException {
for (int i = 1; i <= n; i++) {
while (state != 0) {
Thread.yield();
}
printNumber.accept(0);
if (i % 2 == 1) {
state = 1;
} else {
state = 2;
}
}
}
public void even(IntConsumer printNumber) throws InterruptedException {
for (int i = 2; i <= n; i += 2) {
while (state != 2) {
Thread.yield();
}
printNumber.accept(i);
state = 0;
}
}
public void odd(IntConsumer printNumber) throws InterruptedException {
for (int i = 1; i <= n; i += 2) {
while (state != 1) {
Thread.yield();
}
printNumber.accept(i);
state = 0;
}
}
}
5.ReentrantLock+Condition
class ZeroEvenOdd {
private int n;
private volatile int start = 1;
private volatile int state;
private Lock lock = new ReentrantLock();
private Condition zero = lock.newCondition();
private Condition even = lock.newCondition();
private Condition odd = lock.newCondition();
public ZeroEvenOdd(int n) {
this.n = n;
}
// printNumber.accept(x) outputs "x", where x is an integer.
public void zero(IntConsumer printNumber) throws InterruptedException {
lock.lock();
try {
while (start <= n) {
if (state != 0) {
zero.await();
}
printNumber.accept(0);
if (start % 2 == 0) {
state = 2;
even.signal();
} else {
state = 1;
odd.signal();
}
zero.await();
}
odd.signal();
even.signal();
} finally {
lock.unlock();
}
}
//偶数
public void even(IntConsumer printNumber) throws InterruptedException {
lock.lock();
try {
while (start <= n) {
if (state != 2) {
even.await();
} else {
printNumber.accept(start++);
state = 0;
zero.signal();
}
}
} finally {
lock.unlock();
}
}
//基数
public void odd(IntConsumer printNumber) throws InterruptedException {
lock.lock();
try {
while (start <= n) {
if (state != 1) {
odd.await();
} else {
printNumber.accept(start++);
state = 0;
zero.signal();
}
}
} finally {
lock.unlock();
}
}
}
猜你还喜欢
- 03-29 [编程相关] Winform窗体圆角以及描边完美解决方案
- 03-29 [前端问题] has been blocked by CORS policy跨域问题解决
- 03-29 [编程相关] GitHub Actions 入门教程
- 03-29 [编程探讨] CSS Grid 网格布局教程
- 10-12 [编程相关] python实现文件夹所有文件编码从GBK转为UTF8
- 10-11 [编程算法] opencv之霍夫变换:圆
- 10-11 [编程算法] OpenCV Camshift算法+目标跟踪源码
- 10-11 [Python] python 创建 Telnet 客户端
- 10-11 [编程相关] Python 基于 Yolov8 + CPU 实现物体检测
- 03-15 [脚本工具] 使用go语言开发自动化脚本 - 一键定场、抢购、预约、捡漏
- 01-08 [编程技术] 秒杀面试官系列 - Redis zset底层是怎么实现的
- 01-05 [编程技术] 《Redis设计与实现》pdf
取消回复欢迎 你 发表评论:
- 精品推荐!
-
- 最新文章
- 热门文章
- 热评文章
[资料] 曲黎敏 - 黄帝内经 [MPG]
[书籍] 张九仪《秘传造葬制煞作法》[pdf]
[小说] 武侠小说合集(1912部)
[源码程序] 短剧机器人+付费进群系统,短剧新风口躺赚收益(附源码)
[开发辅助] 开发人员的终极工具箱 | He3(2.0.20.0)
[文件修改] PDF信息修改工具 PDF补丁丁 | PDFPatcher(1.0.1.4234)
[CF探险模式] 地图禁区畅玩攻略,高效获取禁区奖励
[电影] 2024年国产奇幻片《狂暴巨蜥》HD国语中字
[电影] 1984年中国香港经典喜剧片《人吓鬼》蓝光国粤双语中字
[书籍] 席殊实用硬笔字字贴[pdf]
[资料] [大学期末救急课] 猴博士+高斯课堂+斐多课堂,全集视频合集
[云资源] 价值2万元的老男孩Python教程
[书库] 史上最全摄影书推荐(附700本PDF版打包下载)
[云资源] 花了一千多元买的私人健身教程
[下载工具] Internet Download Manager 6.42.7 (IDM)
[影视] 灌篮高手 WEB-DL版下载/Slam Dunk/スラムダンク/灌篮高手:THE FIRST/灌篮高手电影版 2022 The First Slam Dunk 61.35G
[即时通讯] 腾讯QQ PC版9.7.22.29315去广告绿色纯净版
[开发环境] PhpStorm2023中文激活版v2023.3.3 正式版
[图像制作] Adobe Illustrator 2024 v28.1.0.141 破解版
[资料] 3000 套电影电视剧 LOGO 宣传片常用音效合集包
[云资源] 价值2万元的老男孩Python教程
[影视] 灌篮高手 WEB-DL版下载/Slam Dunk/スラムダンク/灌篮高手:THE FIRST/灌篮高手电影版 2022 The First Slam Dunk 61.35G
[云资源] 花了一千多元买的私人健身教程
[书库] 史上最全摄影书推荐(附700本PDF版打包下载)
[电视剧] 三体 (2024) 全8集 网飞版本 中文字幕 合集
[剧集] 繁花 (2023)[全30集][打包]
[影视] 三大队 WEB-DL版下载/Endless Journey/请转告局长,三大队任务完成了 2023 三大队 6.7G
[纪录片] 河西走廊【10集 国语 中文字幕 1080P 10.8G MP4】
[安卓软件] OfficeSuite中文版APP v14.2.50872.0破解版
[影视] 涉过愤怒的海 WEB-DL版下载/怒海 / Across the Furious Sea 2023 涉过愤怒的海 26.3G
- 最新评论
-
谢谢支持!!CC下载站 评论于:03-26 很棒的资源,感谢分享云体风身 评论于:03-26 感谢分享,好东西云体风身 评论于:03-26 谢谢支持!CC下载站 评论于:03-14 央视精品,感谢付出提供。qwer9009 评论于:03-14 谢谢支持!!!CC下载站 评论于:03-13 谢谢分享!Ypc9182 评论于:03-12 谢谢支持!!CC下载站 评论于:03-11 感谢本网站收集和提供这么多的资料,谢谢!Ypc9182 评论于:03-10 很棒的资源,支持一下lingzhi007 评论于:03-10
- 热门tag