【发布时间】:2018-10-14 11:34:07
【问题描述】:
我有检查过的代码,我只想知道我的理解是否正确。我有以下两个课程
public class WaitCheckWaiter implements Runnable
{
WaitCheck wc;
public WaitCheckWaiter( WaitCheck wc )
{
this.wc = wc;
}
@Override
public void run()
{
synchronized ( wc.strList )
{
wc.strList.add( "Added" );
System.out.println( "Notify for others" );
wc.strList.notifyAll();
for ( int i = 0; i < 100; i++ )
{
System.out.println( i );
}
try
{
Thread.sleep( 5000 );
}
catch ( InterruptedException e )
{
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println( "Woke up" );
System.out.println( "After Notifying" );
}
System.out.println( "After synch WaitCheckWaiter" );
}
}
然后是下面这个
public class WaitCheck implements Runnable{
WaitCheck wc;
List<String> strList = new ArrayList();
public static void main(String[] args) {
WaitCheck wc = new WaitCheck();
new Thread(wc).start();
WaitCheckWaiter wcw = new WaitCheckWaiter(wc);
new Thread(wcw).start();
}
@Override
public void run() {
synchronized (strList) {
if(strList.size() == 0)
{
try {
System.out.println("Just Before wait..");
strList.wait();
System.out.println("Just after wait..");
// printing the added value
System.out.println("Value : "+strList.get(0));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
System.out.println("In else statement..!!");
}
}
System.out.println("After synch WaitCheck");
}
}
所以我的理解是,即使我调用 notifyAll(),等待线程也无法恢复,直到调用 notifyAll() 的同步块完成。这是正确的还是有任何其他非确定性行为。
【问题讨论】:
标签: java multithreading synchronized