我创建了一个名为Customer的类,我有两个方法waitThread和 notifyThread。两种方法都将保持相同的锁定obj。在synchronized块的while循环中waitThread将调用wait方法,thread1的锁定被释放,而其他线程称thread2需要用于notifyThread方法并将标志值设置为true。但是我得到的输出是
thread1和thread2都在waitThread方法中输入。他们都没有进入notifyThread方法。任何人都可以建议这里发生了什么,为什么它没有进入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();
}
}
答案 0 :(得分:0)
您首先调用waitThread()
方法,因此两个线程都进入WAIT状态并保持在那里。没有人调用notify()
方法让线程退出WAIT状态。
public void run()
{
waitThread();// HERE, wait is getting called first.
notifyThread(); // control doesn't come here at all.
}