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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 刘士林 中级黑马   /  2012-11-1 18:30  /  1927 人查看  /  6 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

class Demo implements Runnable
{
        public void run()
       {
              for(int x=0; x<20; x++ )
              {
                System.out.println(Thread.curentThread().toString()+"...."+x);
                Thread.yield();//加上这句,实现t1和t2交替运行
              }
       }
}
calss YieldDemo
{
   public static void main(String[] args)
   {
         Demo d = new Demo();
         Thread t1=new Thread(d);
         Thread t2=new Thread(d);
          t1.start();
          t2.start();
          System.out.println("demo over");
   }
}
为什么启动t1、t2后,两个线程都是从0开始打印x,直到19,x存在哪里?两个线程执行的同一个对象的同一个run方法,
应该只有一个x,为什么会有两个呢?难道x在每个线程中都有一份?

评分

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

查看全部评分

6 个回复

倒序浏览
因为x是局部变量
回复 使用道具 举报
x是run方法里的变量,而run方法两个线程都有  我的理解
回复 使用道具 举报
class Demo implements Runnable {
        private int y = 0;//共享的是同一个对象的变量y

        public void run() {//调用方法多次会在栈内存中开辟多个空间,每个方法都是独立的
                for (int x = 0; x < 1000; x++) {
                        System.out
                                        .println(Thread.currentThread().toString() + "...." + y++);
                        Thread.yield();// 注:yield暂停一下该线程,不表示其他线程就能马上获得资源执行
                }
        }
}

评分

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

查看全部评分

回复 使用道具 举报
Thread t1=new Thread(d);
Thread t2=new Thread(d);
因为t1,t2是2个线程,这2个线程是独立的,没关联的

评分

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

查看全部评分

回复 使用道具 举报
模拟该程序的过程:

        Thread t1=new Thread(d)
创建线程t1
        Thread t2=new Thread(d);
创建线程t2         

t1.start();
t1进入就绪状态
         
t2.start();
t2进入就绪状态
         
System.out.println("demo over");
输出 demo over

t1或t2其中一个线程得到执行权 进入run方法(这里假设t1先得到)

t1开始执行run方法
        for(int x=0; x<20; x++ )//t2
              {
                System.out.println(Thread.curentThread().toString()+"...."+x);
                Thread.yield();
              }
T
hread.yield();这条语句 是让线程暂停 进入就绪状态 与其他线程重新竞争cpu执行权 当然谁的优先级高竞争到的机会就多
假设t1暂停被t2得到执行权

t2开始执行run方法
        for(int x=0; x<20; x++ )//t2
              {
                System.out.println(Thread.curentThread().toString()+"...."+x);
                Thread.yield();
              }
注意:t1和t2执行的是各自的run方法,等于t1在执行一个for循环 t2也在执行一个for循环,他们相互竞争执行权 看谁先执行完循环;

故:实际上t1和t2是在执行各自的for循环 程序运行的是两个for循环

评分

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

查看全部评分

回复 使用道具 举报
多线程还没研究,看的挺快的啊

点评

多多学习  发表于 2012-11-2 11:47
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马