gpt4 book ai didi

java - 使用两个线程顺序打印奇偶数

转载 作者:行者123 更新时间:2023-12-01 16:43:40 26 4
gpt4 key购买 nike

我无法理解为什么下面的程序在奇偶场景下不起作用。

我得到的输出是在奇数线程1

如果我理解的话程序执行-

转到 t1 线程。条件不满足。调用notifyAll,它不会被注意到。转到t2线程,该线程打印奇数增量并调用wait()。在这种情况下T2应该开始运行吧?

public class OddEvenTest {

static int max = 20;
static int count = 1;
static Object lock = new Object();

public static void main(String[] args) {

Thread t1 = new Thread(new Runnable() {

@Override
public void run() {
synchronized (lock) {
while(count % 2 == 0 && count < max) {
System.out.println("In even Thread " +count);
count++;
try {
lock.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

lock.notifyAll();
}
}
});

Thread t2 = new Thread(new Runnable() {

@Override
public void run() {
synchronized (lock) {
while(count % 2 != 0 && count < max) {
System.out.println("In Odd Thread " +count);
count++;
try {
lock.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
lock.notifyAll();
}

}
});

t1.start();
t2.start();

}

}

最佳答案

您不想在上同步的循环中盲目地wait()。相反,请检查您等待的先决条件,例如

Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
while (count < max) {
synchronized (lock) {
if (count % 2 == 0) {
System.out.println("In Even Thread " + count);
count++;
lock.notifyAll();
} else {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
});

Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
while (count < max) {
synchronized (lock) {
if (count % 2 != 0) {
System.out.println("In Odd Thread " + count);
count++;
lock.notifyAll();
} else {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
});

在 Java 8+ 中,您可以使用 lambda 来简化匿名类,例如

Thread t1 = new Thread(() -> {
while (count < max) {
synchronized (lock) {
if (count % 2 == 0) {
System.out.println("In Even Thread " + count);
count++;
lock.notifyAll();
} else {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
});

Thread t2 = new Thread(() -> {
while (count < max) {
synchronized (lock) {
if (count % 2 != 0) {
System.out.println("In Odd Thread " + count);
count++;
lock.notifyAll();
} else {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
});

关于java - 使用两个线程顺序打印奇偶数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57335165/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com