关于多线程

I_am_a_java_CaiNiao 2007-10-14 10:45:18
下面程序运行会抛出异常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();
}
}
}


...全文
107 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
qybao 2007-10-16
  • 打赏
  • 举报
回复
synchronized (name) -> synchronized (Test.name)
name.notify() -> Test.name.notify();

leexii 2007-10-16
  • 打赏
  • 举报
回复
InThread,OutThread 有自己的name,声明为static也一样。所以这样的name.wait(),和name.notify()起不到锁的作用
  • 打赏
  • 举报
回复
谢谢大家,我现在把name声明为static了,那说明上述三个类所用的name是同一个了吧,可是运行的时候还是无法输出我输入的字符串啊,请指教,谢谢。(楼上的程序结果跟我的是一样的)
cwjieNo5 2007-10-15
  • 打赏
  • 举报
回复
刚在网上看到一个,觉得和你说的差不多,贴给你看看,一起学习~
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();
}

}

}
}



qybao 2007-10-15
  • 打赏
  • 举报
回复
notify(); -> name.notify(); or name.notifyAll();

forestking_xx 2007-10-15
  • 打赏
  • 举报
回复
另外,你不能保证那个线程先运行,所以肯定有问题
forestking_xx 2007-10-15
  • 打赏
  • 举报
回复
InThread和OutThread中的name是不一样的,你不能把他们当作同一个来使用。。。。。

62,623

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧