Java 不调用notify,只调用wait
我已经创建了一个名为Customer的类,我有两个方法waitThread和 通知线程。这两种方法将持有相同的锁obj。同步块while循环中的waitThread将调用wait方法,thread1的锁被释放,其他线程说thread2需要转到notifyThread方法并将标志值设置为true。但我得到的结果是 thread1和thread2都在waitThread方法中输入。它们都没有进入notifyThread方法。任何人都可以建议这里发生了什么,为什么不输入notifyThread方法。如果需要输入notifyThread,可以做什么Java 不调用notify,只调用wait,java,multithreading,Java,Multithreading,我已经创建了一个名为Customer的类,我有两个方法waitThread和 通知线程。这两种方法将持有相同的锁obj。同步块while循环中的waitThread将调用wait方法,thread1的锁被释放,其他线程说thread2需要转到notifyThread方法并将标志值设置为true。但我得到的结果是 thread1和thread2都在waitThread方法中输入。它们都没有进入notifyThread方法。任何人都可以建议这里发生了什么,为什么不输入notifyThread方法。如
public class Customer implements Runnable
{
public boolean flag=false;
public Object obj=new Object();
public void run()
{
waitThread();
notifyThread();
}
public void waitThread()
{
synchronized(obj)
{
System.out.println(Thread.currentThred().getName()+"in the waitThread");
while(!flag)
{
System.out.println(Thread.currentThred().getName()+"in the waitThread calling wait");
try
{
obj.wait();
}
catch(Exception e)
{
}
}
}
}
public void notifyThread()
{
synchronized(obj)
{
System.out.println(Thread.currentThred().getName()+"in the notifyThread");
flag=true;
System.out.println(Thread.currentThred().getName()+" notify the previous thread");
obj.notify();
}
}
}
}
创建两个线程
public class Test
{
public static void main(String args[])
{
Customer cus=new Customer();
Thread t1=new Thread(cus);
Thread t2=new Thread(cus);
t1.start();
t2.start();
}
}
您首先调用的是
waitThread()
方法,因此两个线程都进入等待状态并保持在等待状态。没有人调用notify()
方法使线程脱离等待状态
public void run()
{
waitThread();// HERE, wait is getting called first.
notifyThread(); // control doesn't come here at all.
}
我不确定您是如何编译代码的,在-
Thread.currentThred()
中存在拼写错误。如果obj.wait()和obj.notify()方法被注释,则控件将转到notifymethod。我认为调用.wait()时需要一些概念