gpt4 book ai didi

java - 线程 :Wait() and notify()

转载 作者:行者123 更新时间:2023-11-29 07:10:03 28 4
gpt4 key购买 nike

执行下面的代码并抛出IllegalMonitorStateException之后 异常(exception)。我收到错误信息:

java.lang.IllegalMonitorStateException
at java.lang.Object.notify(Native Method)
at com.blt.ThreadExample.main(ThreadExample.java:21)

我是多线程新手,我想在代码中使用wait()notify()

package com.blt;



public class ThreadExample implements Runnable {
public static void main(String args[])
{


System.out.println("A");
Thread T = new Thread(new ThreadExample());
Thread T1 = new Thread(new ThreadExample());

System.out.println("B");
try
{
T.setName("thread 1");
T.start();
T1.setName("thread 2");
System.out.println("C");
T.notify();

System.out.println("D");
T1.start();
}
catch(Exception e)
{
e.printStackTrace();
}
}


public void run()
{


synchronized(ThreadExample.class)
{


for(int i=0; i<5; i++)
{

try
{
Thread.currentThread().wait(400);
System.out.println("Inside run=>"+Thread.currentThread().getName());
Thread.currentThread().sleep(2000);




}
catch(Exception e)
{
e.printStackTrace();
}
}
}
}
}

最佳答案

the javadoc 中所述,您需要在使用该对象作为监视器的同步块(synchronized block)中才能对该对象调用 notifywait

Thread.currentThread() 将很难跟踪,所以我建议您使用另一个对象。例如:

public class ThreadExample implements Runnable {

private static final Object lock = new Object();

public static void main(String args[]) {
System.out.println("A");
Thread T = new Thread(new ThreadExample());
Thread T1 = new Thread(new ThreadExample());

System.out.println("B");
try {
T.setName("thread 1");
T.start();
T1.setName("thread 2");
System.out.println("C");
synchronized(lock) {
lock.notify();
}
System.out.println("D");
T1.start();
} catch (Exception e) {
e.printStackTrace();
}
}

public void run() {
synchronized (lock) {
for (int i = 0; i < 5; i++) {
try {
lock.wait(400);
System.out.println("Inside run=>" + Thread.currentThread().getName());
Thread.currentThread().sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}

请注意,您的代码中还有其他几个问题,特别是:

  • 你应该总是在循环中调用 wait(阅读 javadoc 了解更多细节)
  • sleep是一个静态方法,不需要使用Thread.currentThread().sleep(2000); - sleep(2000); 也会这样做。

关于java - 线程 :Wait() and notify(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14811803/

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