A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

黄一—一

注册黑马

  • 黑马币:0

  • 帖子:14

  • 精华:0

© 黄一—一 注册黑马   /  2012-7-11 17:23  /  1115 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 黄一—一 于 2012-7-11 17:47 编辑

代码如下,为什么执行的结果只有syn1在执行,并且是单线程,求高手解答。

public class test4 {
        public static void main(String [] args){
                syn1 ss1=new syn1();
                syn2 ss2=new syn2();
                new Thread(ss1).start();
                        new Thread(ss1).start();
                new Thread(ss2).start();
        }
}


class  syn1 implements Runnable{
        public String str1="";
        public void run() {
                synchronized(str1){
                        while(true){
                                try{Thread.sleep(1);}catch(Exception e){}
                                System.out.println("syn1:"+Thread.currentThread().getName());
                        }
                }
        }        
}

class  syn2 implements Runnable{
        public String str2="";
        public void run() {
                synchronized(str2){
                        while(true){
                                try{Thread.sleep(1);}catch(Exception e){}
                                System.out.println("syn2:"+Thread.currentThread().getName());
                        }
                }
        }
}

2 个回复

倒序浏览
public class Test {

         public static void main(String [] args){
         syn1 ss1=new syn1();
         syn2 ss2=new syn2();
         new Thread(ss1).start();
                 new Thread(ss1).start();
         new Thread(ss2).start();
}

}
class  syn1 implements Runnable{
    public String str1=new String("");//改成new String("");
    public void run() {
            synchronized(str1){
                    while(true){
                            try{Thread.sleep(1);}catch(Exception e){}
                            System.out.println("syn1:"+Thread.currentThread().getName());
                    }
            }
    }        
}
class  syn2 implements Runnable{
    public String str2=new String("");////改成new String("");
    public void run() {
            synchronized(str2){
                    while(true){
                            try{Thread.sleep(1);}catch(Exception e){}
                            System.out.println("syn2:"+Thread.currentThread().getName());
                    }
            }
    }
}
str1与str2其实是同一个对象,在第一个线程运行时,对该对象上了锁,因此每二个线程阻塞等待。这样写str1=new String("")和str2=new String("")就可以了.

评分

参与人数 2技术分 +1 黑马币 +1 收起 理由
蒋映辉 + 1
黄一—一 + 1 赞一个!

查看全部评分

回复 使用道具 举报
学习。谢谢楼上热心解答。
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马