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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 张榆 中级黑马   /  2012-10-2 08:38  /  1550 人查看  /  8 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

class Test implements Runnable {
        public synchronized void run() {
                while (true) {
                        System.out.println(Thread.currentThread().getName() + ".....");
                }
        }

}

public class TestDemo {
        public static void main(String[] args) {
                Test t = new Test();
                Thread t1 = new Thread(t);
                Thread t2 = new Thread(t);

                t1.start();
                t2.start();
       //为什么只看到0号线程了。。。
        }
}

评分

参与人数 1技术分 +1 收起 理由
唐志兵 + 1 赞一个!

查看全部评分

8 个回复

倒序浏览
public synchronized void run() {    //因为你在这加了锁,当一个线程调用run方法后,
                                     //就进入while无限循环,就不会释放锁
                                     //另一个线程自然无法调用run方法,所以只显示
                                     //一个线程   
            while (true) {           
                  System.out.println(Thread.currentThread().getName() + ".....");
             }
        }

评分

参与人数 1技术分 +1 收起 理由
唐志兵 + 1 赞一个!

查看全部评分

回复 使用道具 举报
class Test implements Runnable {
        //你在这加了同步,所以只有一个线程在调用run()方法
        public synchronized void run() {
                while (true) {
                        //在这里while一直循环执行下去,run方法无法结束,所以只能打印一个线程
                        System.out.println(Thread.currentThread().getName() + ".....");
                        //可以再这里加入一个break;
                }
        }

}

public class TestDemo {
        public static void main(String[] args) {
                Test t = new Test();
                Thread t1 = new Thread(t);
                Thread t2 = new Thread(t);

                t1.start();
                t2.start();
       //为什么只看到0号线程了。。。
        }
}
回复 使用道具 举报
其实关于同步。你肯定是和老师卖的售票例子弄混了。

你要知道,同步是同步的哪

public synchronized void run() {//同步不应该同步的run方法,而是 while 里面的多条语句               
               while (true) {
                        System.out.println(Thread.currentThread().getName() + ".....");
                }
        }

回复 使用道具 举报
要看到1线程,那就让0线程先释放执行权一会,同时也释放锁一会,那么1线程就能执行了!
回复 使用道具 举报
因为Test类里面的run方法是无限循环,而它又加了同步状态,所以当线程t1启动时,它会进入到方法中无限循环不会释放锁,t2进不去。所以执行的会一直是一个线程。
回复 使用道具 举报
你这个代码不是 加了  synchronized 么,既然你给其上锁了,然后你又没有将其释放,t1就一直占用着它了,t2自然进不来的,所以只会输出0号线程了。。。。
回复 使用道具 举报
class Test implements Runnable {
        public synchronized void run() {
                while (true) {//有两种解决方案:1,把while(true){}循环结构去掉。2,不去除循环,但在再循环内加入跳转语句如:break即可。
                        System.out.println(Thread.currentThread().getName() + ".....");
                }
        }

}

public class TestDemo {
        public static void main(String[] args) {
                Test t = new Test();
                Thread t1 = new Thread(t);
                Thread t2 = new Thread(t);

                t1.start();
                t2.start();
       //为什么只看到0号线程了。。。        }
}
回复 使用道具 举报
张瑜,你进黑马了没
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马