java - 通过两个类实现 Runnable 打印奇数和偶数,一个是奇数逻辑,另一个是偶数逻辑
问题描述
尝试通过 PrintOddClass 甚至通过 PrintEvenClass 打印奇数 我曾经通过 PrintOddEvenNumberTwoThreads 启动这两个线程,但无法实现它们。就像 1 2 3 4 等等在打印 1 2 之后我猜它会进入死锁状态。
也使用了 join() 方法,但它没有用。我只想通过这种方式实现这一目标。
public class PrintOddEvenNumberTwoThreads {
public static void main(String[] args) throws InterruptedException {
int N = 20;
Thread t1 = new Thread(new PrintOddNumber(N), "OddThread");
Thread t2 = new Thread(new PrintEvenNumber(N), "EvenThread");
t1.start();
t2.start();
}
}
class PrintOddNumber implements Runnable {
private int limit;
private int num = 1;
public PrintOddNumber(int limit) {
this.limit = limit;
}
public void run() {
synchronized(this) {
while(num < limit) {
if(num % 2 != 0) {
try {
System.out.println(num);
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
num++;
notify();
}
}
}
}
class PrintEvenNumber implements Runnable {
private int limit;
private int num = 1;
public PrintEvenNumber(int limit) {
this.limit = limit;
}
public void run() {
synchronized(this) {
while(num < limit) {
if(num % 2 == 0) {
System.out.println(num);
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
num++;
notify();
}
}
}
}
解决方案
推荐阅读
- java - 在java中检查表达式每个部分的null的最佳方法
- perforce - 如何在进行同步之前检索特定流的大小
- java - 复制所有值列表
直接到 Jackson JsonGenerator Array 而不是循环它 - python - 如何将列表的所有元素转换为数字?
- reactor-netty - Netty Http客户端是JEE环境
- python - 在对任何数据结构执行某种方法时,何时将变量分配给自身?
- javascript - 如何在反应js中的组件渲染之前进行api调用
- javascript - 如何使用 javascript 在 mozilla firefox 中获取特定选项卡的 HTML
- java - 如何按自定义顺序对字符串数组进行排序?
- windows - 在 OAuth2 流程中,我们可以将身份验证委托给 Windows SSO