gpt4 book ai didi

java - 使用两个不同的线程打印偶数和奇数

转载 作者:行者123 更新时间:2023-12-03 13:07:51 24 4
gpt4 key购买 nike

我试图运行这段代码,但它卡住了。我不想使用可运行的方法。只是想知道我在这里做错了什么。

package com.learning.threads;

public class OddThread extends Thread {

private Integer count;
Object lock;

public OddThread(Integer count,Object lock) {
this.count = count;
this.lock=lock;
}

@Override
public void run() {

while (count<1000) {
synchronized (lock) {
System.out.println("sdsd"+(count.intValue() % 2));
if ((count.intValue() % 2) == 0) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}

} else {
System.out.println("printing the odd number" + count);
count++;
lock.notify();
}

}

}
}
}


package com.learning.threads;

public class EvenThread extends Thread {


private Integer count;

Object lock;

public EvenThread(Integer count,Object lock){
this.count=count;
this.lock=lock;
}

public void run(){

while(count < 1000){
synchronized (lock) {
System.out.println((count.intValue()%2));
if((count.intValue()%2)!=0){
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}


}else{
System.out.println("printing the even number"+ ++count);

lock.notify();
}

}


}

}

}
public class ThreadClass {

public static void main(String[] args) {


Integer count=new Integer(1);

Object lock=new Object();

EvenThread even=new EvenThread(count,lock);

OddThread odd=new OddThread(count,lock);

odd.start();
even.start();


}

最佳答案

这样做似乎是一种奇怪的方式。作业?

无论如何,所以我想我知道你在尝试什么,但是使用通知来回翻转,但我认为它不会像你期望的那样工作。

您正在调用等待并通知锁定,但您仍处于同步块(synchronized block)中。一次只能有一个线程在该 block 中。您需要让它退出该 block ,然后尝试通知其他人。这意味着重做你的代码以退出,然后在同步块(synchronized block)之外尝试等待/通知代码。与你如何做可能对你有用的增量。

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

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