【发布时间】:2020-03-15 18:41:50
【问题描述】:
我为打印零偶奇问题的leetcode问题尝试了以下代码。 在测试最简单的输入时,它向我显示 Time Limit Exceeded 错误。 有人可以提出一些建议吗? https://leetcode.com/problems/print-zero-even-odd
class ZeroEvenOdd {
private int n;
public ZeroEvenOdd(int n) {
this.n = n;
}
// printNumber.accept(x) outputs "x", where x is an integer.
boolean z = true;
public void zero(IntConsumer printNumber) throws InterruptedException {
for(int i = 1; i <= n; i++) {
if(z) {
printNumber.accept(0);
}
z = false;
odd = !odd;
try { notifyAll(); } catch(Exception e){}
do { try { wait(); } catch(Exception e){ } } while(!z);
}
}
boolean odd = false;
public void even(IntConsumer printNumber) throws InterruptedException {
for(int i = 1; i <= n; i++) {
do { try { wait(); } catch(Exception e){ } } while(z || odd);
if(!odd && !z && i%2 == 0) {
printNumber.accept(i);
}
z = true;
try { notifyAll(); } catch(Exception e){}
}
}
public void odd(IntConsumer printNumber) throws InterruptedException {
for(int i = 1; i <= n; i++) {
do { try { wait(); } catch(Exception e){ } } while(z || !odd);
if(odd && !z && i%2 == 1) {
printNumber.accept(i);
}
z = true;
try { notifyAll(); } catch(Exception e){}
}
}
}
【问题讨论】:
标签: java multithreading