gpt4 book ai didi

java - 同时运行两个线程

转载 作者:行者123 更新时间:2023-12-02 04:12:47 25 4
gpt4 key购买 nike

我正在尝试同时打印两个线程的名称。任何人都可以建议我做错了什么吗?我收到“IllegalMonitorStateException

//奇数线程可运行 公共(public)类 OddThread 实现 Runnable {

    MainClass obj;
public OddThread(MainClass obj) {
// TODO Auto-generated constructor stub
this.obj= obj;
}
public void run() {
int number=1;
while(number <10)
{
obj.PrintNumbers();
notifyAll();
try {
wait();
} catch (InterruptedException e) {System.out.println("Exception in wait of OddThread");
}
number = number+2;

}

}

}

//即使线程可运行

public class EvenThread implements Runnable{

MainClass obj;
public EvenThread(MainClass obj)
{
this.obj=obj;
}
public void run() {
int number=0;
while(number<=10)
{
obj.PrintNumbers();
notifyAll();
try {
wait();
} catch (InterruptedException e) {
System.out.println("Exception in wait of EvenThread");
}
number = number+2;
}

}

}

//主类

public class MainClass {
public static void main(String[] args)
{
MainClass obj = new MainClass();
// Boolean flag= true;
EvenThread evenThread = new EvenThread(obj);
OddThread oddThread = new OddThread(obj);
Thread Even = new Thread(evenThread);
Thread Odd = new Thread(oddThread);
Even.setName("Even Thread");
Odd.setName("Odd Thread");
Even.start();
Odd.start();
}

public synchronized void PrintNumbers()
{
System.out.println(Thread.currentThread().getName());
}

}

我得到的输出是偶数线程奇数线程线程“偶数线程”中的异常 线程“奇数线程”中的异常 java.lang.IllegalMonitorStateException

最佳答案

您应该将 notifyAll()wait() 包含在 synchronized (this) {} 中像:

synchronized (this) {
notifyAll();
}

synchronized (this) {
wait();
}

这些方法 notify()notifyAll()wait() 只能由该方法的所有者的线程调用对象的监视器,因此您必须将它们包围在同步块(synchronized block)中,如所述 Here the Object Java doc

关于java - 同时运行两个线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33624993/

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