本文介绍了线程:Wait()和notify()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
执行以下代码并抛出IllegalMonitorStateException
例外.我收到以下错误消息:
After execution the below code and throwing IllegalMonitorStateException
exception. I am getting error as:
java.lang.IllegalMonitorStateException
at java.lang.Object.notify(Native Method)
at com.blt.ThreadExample.main(ThreadExample.java:21)
我是多线程技术的新手,我想在代码中使用wait()
和notify()
.
I am new in multithreading, I want to use wait()
and notify()
in the code.
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();
}
}
}
}
}
推荐答案
尝试一下..让我知道你是否有疑问.
Try this.. and let me know if you have any doudt.
package com.blt;
public class ThreadExample implements Runnable {
public static void main(String args[]) {
Thread T1 = new Thread(new ThreadExample());
Thread T2 = new Thread(new ThreadExample());
try {
T1.setName("thread 1");
T1.start();
T2.setName("thread 2");
T2.start();
} catch (Exception e) {
e.printStackTrace();
}
}
public void run() {
synchronized (ThreadExample.class) {
for (int i = 0; i < 5; i++) {
try {
ThreadExample.class.notify();
System.out.println("Thread going to wait state::"+ Thread.currentThread().getName());
ThreadExample.class.wait(400);
System.out.println("Thread notified is::"+ Thread.currentThread().getName());
System.out.println("Thread going to sleep state::"+ Thread.currentThread().getName());
Thread.sleep(2000);
System.out.println("==========");
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
这篇关于线程:Wait()和notify()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!