下面程序运行会抛出异常java.lang.IllegalMonitorStateException原因为:某一线程已经试图等待对象的监视器,或者试图通知其他正在等待对象的监视器而本身没有指定监视器的线程。
可是我明明把两个线程都指定了监视器了。请指教。谢谢import java.util.*;
import java.io.*;public class Test
{
public String name;
public Test()
{
name = "";
}
public static void main(String args[])
{
Thread thread_1=new Thread(new InThread());
Thread thread_2=new Thread(new OutThread());
thread_1.start();
thread_2.start();
}
}class InThread extends Test implements Runnable
{
public InThread()
{
}
public void run()
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
synchronized (name)
{
try
{
System.out.println("请输入:");
name=br.readLine();
notify();
}
catch (Exception e)
{
}
}
}
}class OutThread extends TestPub implements Runnable
{
public OutThread()
{
}
public void run()
{
synchronized (name)
{
System.out.println("输出结果为:" + name);
notify();
}
}
}
可是我明明把两个线程都指定了监视器了。请指教。谢谢import java.util.*;
import java.io.*;public class Test
{
public String name;
public Test()
{
name = "";
}
public static void main(String args[])
{
Thread thread_1=new Thread(new InThread());
Thread thread_2=new Thread(new OutThread());
thread_1.start();
thread_2.start();
}
}class InThread extends Test implements Runnable
{
public InThread()
{
}
public void run()
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
synchronized (name)
{
try
{
System.out.println("请输入:");
name=br.readLine();
notify();
}
catch (Exception e)
{
}
}
}
}class OutThread extends TestPub implements Runnable
{
public OutThread()
{
}
public void run()
{
synchronized (name)
{
System.out.println("输出结果为:" + name);
notify();
}
}
}
解决方案 »
- java递归求解1-5阶乘之和
- javac 是如何编译多个文件的
- java 与 网页的问题
- 如何获取物理路径????
- 把某个服务器短运行的jar反编译过来的源码(大概有上百个文件),经过自己的修改后打jar包能否和原来的jar一样能正常运行? 今天揭帖.
- 120分 求一简单配置问题 !!!谢谢 !!
- 询问String 下的charAt()函数异常
- 用java写记事本
- 请各位前辈帮帮忙!!!!
- 为什么ResultSet不能用于递归程序中 ErrMsg :java.sql.SQLException: ResultSet is closed
- 在JAVA学习中会使用到JAVA帮助文档(希望高手能交点怎样去使用API文档的方法)
- 高手救命..关于JTable和数据库的....
import java.io.*;
import java.io.*; class practice_2 {
public boolean canout = false;
public String str = null; public static void main(String[] args) {
practice_2 pr = new practice_2();
new out(pr).start();
new in(pr).start();
}
}
class out extends Thread {
public practice_2 pr; public out(practice_2 pr) {
this.pr = pr;
} public void run() {
while (true) {
try {
synchronized (pr) {
if (!pr.canout) {
pr.wait();
}
System.out.println(" > > >" + pr.str);
pr.notifyAll();
pr.canout = false;
}
} catch (InterruptedException ex) {
ex.printStackTrace();
} }
}
}
class in extends Thread { public practice_2 pr;
BufferedReader reader = null; public in(practice_2 pr) {
this.pr = pr;
reader = new BufferedReader(new InputStreamReader(System.in));
} public void run() {
while (true) {
try {
synchronized (pr) {
if (pr.canout) {
pr.wait();
}
System.out.println("请输入:");
pr.str = reader.readLine();
pr.notifyAll();
pr.canout = true;
}
} catch (Exception ex) {
ex.printStackTrace();
} } }
}
name.notify() -> Test.name.notify();