Java 如果我正在等待一个不可运行的对象怎么办?
考虑以下代码:-Java 如果我正在等待一个不可运行的对象怎么办?,java,multithreading,wait,notify,Java,Multithreading,Wait,Notify,考虑以下代码:- public class UsingWait1{ public static void main(String... aaa){ CalculateSeries r = new CalculateSeries(); Thread t = new Thread(r); t.start(); synchronized(r){ try{ r.wait(); //Here I am waiting on an
public class UsingWait1{
public static void main(String... aaa){
CalculateSeries r = new CalculateSeries();
Thread t = new Thread(r);
t.start();
synchronized(r){
try{
r.wait(); //Here I am waiting on an object which is Runnable. So from its run method, it can notify me (from inside a synchronized block).
} catch (InterruptedException e) {
System.out.println("Interrupted");
}
}
System.out.println(r.total);
try{
Thread.sleep(1);
} catch (InterruptedException e){
System.out.println("Interrupted");
}
System.out.println(r.total);
}
}
class CalculateSeries implements Runnable{
int total;
public void run(){
synchronized(this){
for(int i = 1; i <= 10000; i++){
total += i;
}
notify(); // Line 1 .. Notify Exactly one of all the threads waiting on this instance of the class to wake up
}
}
}
这里我在第2行得到一个非法的MonitorStateException。在调用wait()和notify()时,我正在等待对象的同一个实例(不可运行)。那有什么问题
是否有人能给出一些场景,在其中等待不可运行的对象是有用的???等待不需要处于可运行状态。这就是为什么notify()处于启用状态而未处于启用状态。我想这在所有情况下都有帮助,我们希望避免忙碌的等待 问题似乎是synchronized()在nr上,而notify是在不同的对象上调用的。还应在最终变量上进行同步
class IAmRunnable implements Runnable {
final NotRunnable nr;
IAmRunnable( final NotRunnable nr) {
this.nr = nr;
}
public void run() {
synchronized (nr) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Sleeping Interrupted :( ");
}
nr.notify(); // Line 2
}
}
}
等待不需要处于可运行状态。这就是为什么notify()处于启用状态而未处于启用状态。我想这在所有情况下都有帮助,我们希望避免忙碌的等待 问题似乎是synchronized()在nr上,而notify是在不同的对象上调用的。还应在最终变量上进行同步
class IAmRunnable implements Runnable {
final NotRunnable nr;
IAmRunnable( final NotRunnable nr) {
this.nr = nr;
}
public void run() {
synchronized (nr) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Sleeping Interrupted :( ");
}
nr.notify(); // Line 2
}
}
}
这不是有点像等一辆没有轮子的公共汽车吗?那条线不应该是nr.notify()吗;这不是有点像等一辆没有轮子的公共汽车吗?那条线不应该是nr.notify()吗;哦,是的。那真是一个愚蠢的小姐!同样,您关于在同步中使用最终变量的建议也很有用:)哦,是的。那真是一个愚蠢的小姐!同样,您关于在同步中使用final变量的建议也很有用:)