| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 801 人关注过本帖
标题:各位大神帮我看看一个有关线程的代码
只看楼主 加入收藏
a1019594256
Rank: 1
等 级:新手上路
帖 子:1
专家分:0
注 册:2016-11-4
结帖率:0
收藏
已结贴  问题点数:20 回复次数:1 
各位大神帮我看看一个有关线程的代码
各位大神帮我看看这代码,我有个问题,在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){}
            
        }
    }

}
搜索更多相关主题的帖子: public 
2016-11-04 01:04
JenkinXiao
Rank: 2
等 级:论坛游民
帖 子:1
专家分:20
注 册:2016-11-4
收藏
得分:20 
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();
    }
}
2016-11-04 14:33
快速回复:各位大神帮我看看一个有关线程的代码
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.018124 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved