首页新闻找找看学习计划

java CountDownLatch 入门实例出现java.lang.IllegalMonitorStateException

0
悬赏园豆:5 [已关闭问题] 关闭于 2015-11-29 00:19
import java.util.concurrent.CountDownLatch;

public class CDDemo
{
    public static void main(String[] args)
    {
        CountDownLatch cd = new CountDownLatch(3);
    
        new Racer(cd, "A").start();
        new Racer(cd, "B").start();
        new Racer(cd, "C").start();
        
        for(int i=0; i<3; i++)
        {
            try
            {
                Thread.sleep(1000);
                cd.countDown();
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
            
            System.out.println(i);
        
            if(i == 2)
                System.out.println("start");
        }
        
    }
}
class Racer extends Thread
{
    private CountDownLatch countDownLatch;
    
    public Racer(CountDownLatch countDownLatch, String name)
    {
        setName(name);
        this.countDownLatch = countDownLatch;
    }
    @Override
    public void run()
    {
        try
        {
                countDownLatch.wait();
        }
        catch (InterruptedException e1)
        {
            e1.printStackTrace();
        }
        for(int i=0; i<3; i++)
        {
            System.out.println(getName()+" : "+i);
        }
    }
}

Exception in thread "B" Exception in thread "C" Exception in thread "A" java.lang.IllegalMonitorStateException
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:503)
at com.lzyer.bingfa.Racer.run(CDDemo.java:49)
java.lang.IllegalMonitorStateException
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:503)
at com.lzyer.bingfa.Racer.run(CDDemo.java:49)
java.lang.IllegalMonitorStateException
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:503)
at com.lzyer.bingfa.Racer.run(CDDemo.java:49)

刚刚学习这部分内容,求解,谢谢。

lzyer的主页 lzyer | 初学一级 | 园豆:130
提问于:2015-11-29 00:14
< >
分享
所有回答(1)
2

自己太粗心了将countDownLatch.await();写成了countDownLatch.wait();

lzyer | 园豆:130 (初学一级) | 2015-11-29 00:19
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册