0
点赞
收藏
分享

微信扫一扫

LeetCode(多线程)- 1116. 打印零与奇偶数


题目链接:​​点击打开链接​​

题目大意:略。

解题思路:略。

相关企业

  • 爱奇艺

AC 代码

// 解决方案(1)
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 = 0; i < n; i++) {
while (state != 0) {
Thread.yield();
}
printNumber.accept(0);
if (i % 2 == 0) {
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;
}
}
}

// 解决方案(2)
class ZeroEvenOdd {

private int n;

private volatile int type = 0;

private volatile boolean flag = true;

private final Object obj = new Object();

private volatile int num = 1;

public ZeroEvenOdd(int n) {
this.n = n;
}

// printNumber.accept(x) outputs "x", where x is an integer.
public void zero(IntConsumer printNumber) throws InterruptedException {
while (true) {
synchronized (obj) {
while (type != 0) {
obj.wait();
}

if (num > n) {
flag = false;
obj.notifyAll();
return;
}

printNumber.accept(0);
if (num % 2 == 1) {
type = 1;
} else {
type = 2;
}
obj.notifyAll();
}
}
}

public void even(IntConsumer printNumber) throws InterruptedException {
while (true) {
synchronized (obj) {
while (flag && type != 2) {
obj.wait();
}

if (num > n) {
obj.notifyAll();
return;
}

printNumber.accept(num++);
type = 0;
obj.notifyAll();
}
}
}

public void odd(IntConsumer printNumber) throws InterruptedException {
while (true) {
synchronized (obj) {
while (flag && type != 1) {
obj.wait();
}

if (num > n) {
obj.notifyAll();
return;
}

printNumber.accept(num++);
type = 0;
obj.notifyAll();
}
}
}
}


举报

相关推荐

0 条评论