运行如下程序抛出异常:
public class Agg {
public static void main(String argv[]) {
Agg a = new Agg();
a.go();
}
public void go() {
DSRoss ds1 = new DSRoss("one");
ds1.start();
}
}class DSRoss extends Thread {
private String sTname = "";
DSRoss(String s) {
sTname = s;
}
public void run() {
notwait();
System.out.println("finished");
} public void notwait() {
while (true) {
try {
System.out.println("waiting");
wait();
}
catch (InterruptedException ie) {
}
System.out.println(sTname);
notifyAll();
}
}
}
调试的时候提示wait()这里有错误:Object synchronization method was called from an unsynchronized block of code.
请问为什么这里错误,如何更改呢?
public class Agg {
public static void main(String argv[]) {
Agg a = new Agg();
a.go();
}
public void go() {
DSRoss ds1 = new DSRoss("one");
ds1.start();
}
}class DSRoss extends Thread {
private String sTname = "";
DSRoss(String s) {
sTname = s;
}
public void run() {
notwait();
System.out.println("finished");
} public void notwait() {
while (true) {
try {
System.out.println("waiting");
wait();
}
catch (InterruptedException ie) {
}
System.out.println(sTname);
notifyAll();
}
}
}
调试的时候提示wait()这里有错误:Object synchronization method was called from an unsynchronized block of code.
请问为什么这里错误,如何更改呢?
而且括号里面要加上毫妙数..
btw,wait方法可以不带参数
D:\java\new>java Agg
waiting
Exception in thread "Thread-0" java.lang.IllegalMonitorStateException
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:484)
at DSRoss.notwait(Agg.java:26)
at DSRoss.run(Agg.java:18)抛出的"IllegalMonitorStateException"异常 查API=="抛出的异常表明某一线程已经试图等待对象的监视器,或者试图通知其他正在等待对象的监视器而本身没有指定监视器的线程." 也就是说该线程没有指定对象监视器.
通过以下三种方法之一,线程可以成为此对象监视器的所有者:
1:通过执行此对象的同步 (Sychronized) 实例方法。
2:通过执行在此对象上进行同步的 synchronized 语句的正文。
3:对于 Class 类型的对象,可以通过执行该类的同步静态方法。
!!一次只能有一个线程拥有对象的监视器。 也就是说你的程序在执行到wait()发现"当前的线程不是此对象监视器的所有者".所以解决的办法 因该是让当前线程成为此对象监视器的所有者. 按方法1来做:
改后的代码为:
public synchronized void notwait() {
while (true) {
try {
System.out.println("waiting");
wait(2000);
}
catch (InterruptedException ie) {
}
System.out.println(sTname);
notifyAll();
}
}
应该这样就可以了~~我也是新手 刚刚学习,发点意见讨论讨论.要有错误还请指教哈!!