注册 登录
编程论坛 JAVA论坛

各位大神帮我看看一个有关线程的代码

a1019594256 发布于 2016-11-04 01:04, 978 次点击
各位大神帮我看看这代码,我有个问题,在run方法前加了synchronized修饰,其实就相当于单线程了,这个程序测试也正常,运行时Thread-0和Thread-1屏幕只会一直打印一种。可是我在里面加了wait方法后,每次执行都会同时打印出Thread-0和Thread-1两个然后线程等待状态。按说加了synchronized修饰,run方法只可以有一个线程进来。怎么这个执行了wait方法后另一个线程也会进来?
public class  test
{
    public static void main(String[] args)
    {
        Thread_A t = new Thread_A();
        
        Thread t1 = new Thread(t);
        Thread t2 = new Thread(t);
        t1.start();
        t2.start();
    }
}

class Thread_A implements Runnable
{

    public synchronized void run()
    {
        while(true)
        {
            System.out.println(Thread.currentThread().getName());
            //try{ wait();}catch(Exception e){}
            
        }
    }

}
1 回复
#2
JenkinXiao2016-11-04 14:33
wait()挂起线程的同时会释放锁的,你想只有一个线程进来就用sleep,这样锁被持有就可以实现你要的效果了。
如果非要用wait()实现也可以在加一层synchronized
public class Test {
    public static void main(String[] args)
    {
        Thread_A t = new Thread_A();
        
        Thread t1 = new Thread(t);
        Thread t2 = new Thread(t);
        t1.start();
        t2.start();
    }
   
    public synchronized void print(){
        while(true)
        {
            System.out.println(Thread.currentThread().getName());
            try{ wait();}catch(Exception e){}
        }
    }
}

class Thread_A implements Runnable
{

    public synchronized void run()
    {
        Test t = new Test();
        t.print();
    }
}
1