日期:2014-05-20  浏览次数:20843 次

多线程问题~~~~~~~~~~
我写2个线程,线程1一直执行,线程2不定时执行,当线程2想执行时,线程1就要停下来让线程2执行。

我像下面这么写行吗? 这不能让这两个线程同时执行,用synchronized没错吧

可我一执行程序就java.lang.IllegalMonitorStateException。指定错误行数是wait()和notify()这两行都错了

谁能指点一下~~~~~谢谢


Java code

public class Test
{    
    Object o = new Object();
    boolean b = false;
        
    public static void main(String[] args)
    {
        new Thread(new Thread1()).start();
        new Thread(new Thread2()).start();    
    }

    private class Thread1 implements Runnable
    {
        public void run()
        {        
            a();                
        }            
        private void a() throws InterruptedException
        {            
            synchronized(o)
            {
                if(b)
                {
                    wait();
                }
                //执行内容 
            }        
        }        
    }
        
        
    private class Thread2 implements Runnable
    {
        public void run()
        {        
            b();                            
        }
            
        private void b() throws InterruptedException
        {
            b = true;
                
            synchronized(o)
            {
                //执行内容                    
                b = false;
                notify();            
            }
                
        }
    }
}



------解决方案--------------------
对象锁搞错当然要有异常了,在synchronized里的wait ,notify要由对象锁所调用,
你写的是Test类来调用。
------解决方案--------------------
改为o.wait()和o.notity()