【发布时间】:2012-08-18 23:31:42
【问题描述】:
抱歉我的格式不正确。我正在使用记事本编写程序。
这是一个有效的代码。我唯一的问题是,我已经读过必须在同步块中使用通知和等待。但是,在下面的示例中,在同步块中没有使用等待和通知,并且仍然没有抛出错误。
class counthrd implements Runnable {
Thread thrd;
String x;
counthrd cnt1;
counthrd() {
}
boolean suspended;
boolean stopped;
counthrd(String s, counthrd cnt1) {
thrd = new Thread(this, s);
this.cnt1 = cnt1;
thrd.start();
x = s;
}
public void run() {
try {
System.out.println("Starting " + thrd.currentThread().getName());
for (int i = 1; i < 100; i++) {
System.out.print(i + " ");
if ((i % 10) == 0) {
System.out.println();
Thread.sleep(500);
}
//synchronized(cnt1){
while (suspended) {
System.out.println("going to wait mode");
wait();
notify();
}
//}
}
} catch (Exception e) {
System.out.println(e);
}
}
synchronized void suspendme() {
suspended = true;
notify();
}
synchronized void resumeme() {
suspended = false;
notify();
}
}
class counter {
public static void main(String args[]) throws InterruptedException {
counthrd cnt1 = new counthrd();
counthrd cnthrd1 = new counthrd("thrd 1", cnt1);
Thread.sleep(1000);
System.out.println("going to wait mode");
cnt1.suspendme();
Thread.sleep(1000);
System.out.println("resuming");
cnt1.resumeme();
Thread.sleep(1000);
}
}
【问题讨论】:
-
这对你有用吗?通常,wait() 不需要锁定,而 notify() 则需要。
-
您知道,Eclipse 是免费的。它使您可以键入变量名称的第一部分并提出其余部分。这使您的生活更轻松,并允许您使用名称与
"thrd"不同的变量。它还为您进行格式化。 -
那么为什么我的问题被降级了?这是一个真正的问题。
-
根据§17.2.1 of the Java Language Specification,如果线程对
wait的主题缺少锁定,则会抛出IllegalMonitorStateException。 -
@veer “答案是他从来没有真正打电话给
wait。”所以发布。