当前位置: 技术问答>java相关
多线程问题请教
来源: 互联网 发布时间:2015-01-12
本文导语: 为什么调用wait()和notify()就会抛出异常IllegalMonitorStateException?import java.io.*; import java.util.*; class Test { static FileReader inputStream; static FileWriter outputStream; public static void main(String[] args) { T...
为什么调用wait()和notify()就会抛出异常IllegalMonitorStateException?import java.io.*;
import java.util.*;
class Test
{
static FileReader inputStream;
static FileWriter outputStream;
public static void main(String[] args)
{
Test sTest = new Test();
WriteTest writeT = new WriteTest(outputStream, msg);
ReadTest readT = new ReadTest(inputStream);
writeT.start();
readT.start();
}
public Test()
{
try
{
inputStream = new FileReader("temp.txt");
outputStream = new FileWriter("temp1.txt");
}
catch (IOException e) {}
}
}
///////readT.class
import java.io.*;
public class ReadT extends Thread
{
private FileReader in;
public ReadT(FileReader _in)
{
in = _in;
}
public void run()
{
try {
this.sleep(20000);
} catch (InterruptedException e) {}
System.out.println( "reader here" );
notify();
}
}
/////////writeT.class
import java.io.*;
public class WriteSerial extends Thread
{
private String msg;
private FileWriter out;
public WriteSerial(FileWriter _out, String _msg)
{
msg = _msg;
out = _out;
}
public void run()
{
out.write(msg.getBytes());
try
{
wait(5000);
} catch (InterruptedException e) { }
System.out.println("writer here");
}
}
}
import java.util.*;
class Test
{
static FileReader inputStream;
static FileWriter outputStream;
public static void main(String[] args)
{
Test sTest = new Test();
WriteTest writeT = new WriteTest(outputStream, msg);
ReadTest readT = new ReadTest(inputStream);
writeT.start();
readT.start();
}
public Test()
{
try
{
inputStream = new FileReader("temp.txt");
outputStream = new FileWriter("temp1.txt");
}
catch (IOException e) {}
}
}
///////readT.class
import java.io.*;
public class ReadT extends Thread
{
private FileReader in;
public ReadT(FileReader _in)
{
in = _in;
}
public void run()
{
try {
this.sleep(20000);
} catch (InterruptedException e) {}
System.out.println( "reader here" );
notify();
}
}
/////////writeT.class
import java.io.*;
public class WriteSerial extends Thread
{
private String msg;
private FileWriter out;
public WriteSerial(FileWriter _out, String _msg)
{
msg = _msg;
out = _out;
}
public void run()
{
out.write(msg.getBytes());
try
{
wait(5000);
} catch (InterruptedException e) { }
System.out.println("writer here");
}
}
}
|
一个线程必须首先获得某个对象的锁之后,才能使用wait、notify、notifyAll这几个方法,换句话说,也就是必须放在一个synchronized 块中,这是一个基本要求。
而且wait() 没有一个 wait(5000) 这种方法,可能是与sleep()搞混了。
而且wait() 没有一个 wait(5000) 这种方法,可能是与sleep()搞混了。