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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 左华清 黑马帝   /  2012-2-22 17:25  /  2773 人查看  /  4 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 左华清 于 2012-2-23 11:38 编辑

public class ThreadDemo1 {
        public static void main(String[]args){
                TestThread tt=new TestThread();
                new Thread(tt).start();
                tt.str=new String("method");
                new Thread(tt).start();
        }
}
class TestThread implements Runnable{
        int tickets=100;
        String str=new String("");
        public void run(){
                if(str.equals("method")){
                        while(true){
                                sail();
                        }
                }else{
                        while(true){
                                synchronized(str){
                                        if(tickets>0){
                                                try{Thread.sleep(1);}catch(Exception e){};
                                                System.out.println("run():"+Thread.currentThread().getName()+"-----is sailing ticket"+tickets--);
                                        }
                                }
                        }
                }
               
        }
       
        public synchronized void sail(){
                if(tickets>0){
                        try{Thread.sleep(1);}catch(Exception e){};
                        System.out.println("sail():"+Thread.currentThread().getName()+"----is sailing ticket"+tickets--);
                }
        }
}

请大家帮忙指点下,为什么打印结果静是sail().........................

评分

参与人数 1技术分 +1 收起 理由
admin + 1

查看全部评分

4 个回复

倒序浏览
两个线程共享的是一个对象,两个线程里面的str都是method
回复 使用道具 举报
我觉得程序运行是这样的先是运行else中的代码,碰到了sleep,就执行tt.str=new String("method");,Str的值就变成了method,线程o再判断是否是method就一直执行 sail();
,也不太说得清楚,有正确答案请告之让大家一起学习一下呵呵

评分

参与人数 1技术分 +1 收起 理由
admin + 1

查看全部评分

回复 使用道具 举报
个人感觉第一个 new Thread(tt).start();是线程并没有马上去运行run中的内容,而在主线程tt.str=new String("method");后去执行的线程,
你可以在对str修改之前,让主线程去sleep一下,看一下结果
回复 使用道具 举报
谢谢各位,看了几遍视频了。原因正如大家所说的一样,执行的都是函数,不是同步代码块,
同步代码块和同步函数的监视器对象不同, 把synchronized(str)换成syschronized(this)就好了。

线程.start()之后,并不会立即启动执行,只是进入一个准备状态。
接着运行了 tt.str=new String("method");
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马