当前位置: 代码迷 >> J2SE >> 关于多线程,该如何处理
  详细解决方案

关于多线程,该如何处理

热度:147   发布时间:2016-04-24 13:27:20.0
关于多线程
下面程序运行会抛出异常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();
}
}
}




------解决方案--------------------
InThread和OutThread中的name是不一样的,你不能把他们当作同一个来使用。。。。。
------解决方案--------------------
notify(); -> name.notify(); or name.notifyAll();
 

------解决方案--------------------
刚在网上看到一个,觉得和你说的差不多,贴给你看看,一起学习~
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(); 
  相关解决方案