[知识总结] 【leetcode】多线程编程题题解
作者:CC下载站 日期:2021-11-15 03:53:00 浏览:75 分类:编程开发
本文将记录力扣多线程下的题目:
每道题基本都有很多种解法,基本都可以使用变量
、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
取消回复欢迎 你 发表评论:
- 精品推荐!
-
- 最新文章
- 热门文章
- 热评文章
[电视剧] 芈月传 【全集81集全】【未删减版】【国语中字】【2015】【HD720P】【75G】
[电视剧] 封神榜 梁丽版 (1989) 共5集 480P国语无字 最贴近原著的一版【0.98 G】
[影视] 【雪山飞孤4个版本】【1985、1991、1999、2007】【1080P、720P】【中文字幕】【167.1G】
[资料] 24秋初中改版教材全集(全版本)[PDF]
[电影] 高分国剧《康熙王朝》(2001)4K 2160P 国语中字 全46集 78.2G
[动画] 迪士尼系列动画139部 国英双语音轨 【蓝光珍藏版440GB】
[电影] 莫妮卡贝鲁奇为艺术献身电影大合集 1080P超清 双语字幕
[电影] DC电影宇宙系列合集18部 4K 高码率 内嵌中英字幕 273G
[音乐] 【坤曲/4坤时】鸡你太美全网最全,385首小黑子战歌,黄昏见证虔诚的信徒,巅峰诞生虚伪的拥护!
[音乐] 用餐背景音乐大合集 [MP3/flac]
[书籍] 彭子益医书合集 [PDF/DOC]
[游戏] 《黑神话悟空》免安装学习版【全dlc整合完整版】+Steam游戏解锁+游戏修改工具!
[动画] 《名侦探柯南》名侦探柯南百万美元的五菱星 [TC] [MP4]
[电视剧集] [BT下载][黑暗城市- 清扫魔 Dark City: The Cleaner 第一季][全06集][英语无字][MKV][720P/1080P][WEB-RAW]
[动画] 2002《火影忍者》720集全【4K典藏版】+11部剧场版+OVA+漫画 内嵌简日字幕
[剧集] 《斯巴达克斯》1-4季合集 无删减版 1080P 内嵌简英特效字幕
[CG剧情] 《黑神话:悟空》158分钟CG完整剧情合集 4K120帧最高画质
[短剧] 被下架·禁播的羞羞短剧·午夜短剧合集
[游戏] 黑神话悟空离线完整版+修改器
[图像处理] 光影魔术手v4.6.0.578绿色版
[影视] 美国内战 4K蓝光原盘下载+高清MKV版/内战/帝国浩劫:美国内战(台)/美帝崩裂(港) 2024 Civil War 63.86G
[影视] 一命 3D 蓝光高清MKV版/切腹 / 切腹:武士之死 / Hara-Kiri: Death of a Samurai / Ichimei 2011 一命 13.6G
[影视] 爱情我你他 蓝光原盘下载+高清MKV版/你、我、他她他 2005 Me and You and Everyone We Know 23.2G
[影视] 穿越美国 蓝光原盘下载+高清MKV版/窈窕老爸 / 寻找他妈…的故事 2005 Transamerica 20.8G
[电影] 《黄飞鸿》全系列合集
[Android] 开罗游戏 ▎像素风格的模拟经营的游戏厂商安卓游戏大合集
[游戏合集] 要战便战 v0.9.107 免安装绿色中文版
[书籍] 彭子益医书合集 [PDF/DOC]
[资源] 精整2023年知识星球付费文合集136篇【PDF格式】
[系统]【黑果小兵】macOS Big Sur 11.0.1 20B50 正式版 with Clover 5126 黑苹果系统镜像下载
- 最新评论
-
谢谢分享感谢ppy2016 评论于:11-05 谢谢分享感谢ppy2016 评论于:11-05 怎么没有后续闲仙麟 评论于:11-03 怎么没后续闲仙麟 评论于:11-03 有靳东!嘻嘻奥古斯都.凯撒 评论于:10-28 流星花园是F4处女作也是4人集体搭配的唯一一部!奥古斯都.凯撒 评论于:10-28 找了好久的资源,终于在这里找到了。感谢本站的资源和分享。谢谢AAAAA 评论于:10-26 找了好久的资源,终于在这里找到了。感谢本站的资源和分享。谢谢password63 评论于:10-26 找了好久的资源,终于在这里找齐了!!!!blog001 评论于:10-21 找了好久的资源,终于在这里找齐了!!!!blog001 评论于:10-21
- 热门tag