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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 张扬 黑马帝   /  2011-8-5 10:08  /  1799 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

class S implements Runnable {
        public S() {
                System.out.println("Runnable starts!");
        }
        public void run() {
                for(int i=0;i<3;i++) {
                        System.out.println("Runnable");
                }
        }
}

public class A extends Thread {
        public A() {
                System.out.println("Thread Starts!");
        }
        public void run() {
                for(int i=0;i<3;i++) {
                        System.out.println("Thread");
                }
        }
        public static void main(String[] args) {
                new Thread(new S()).start();
                new A().start();
        }
}
输出结果
Runnable starts!
Thread Starts!
Runnable
Runnable
Runnable
Thread
Thread
Thread
为什么不是
Runnable starts!
Thread Starts!
Runnable
Thread
Runnable
Thread
Runnable
Thread

2 个回复

倒序浏览
黑马网友  发表于 2011-8-5 11:07:48
沙发

回复 楼主 的帖子

用张老师说的话就是  我抢了篮球还可以去接着抢,并不是这次我抢了下次就给你抢。
回复 使用道具 举报
要看效果的话把你的代码加了几句:
  1. class S implements Runnable  {
  2.         public S() {
  3.                 System.out.println("Runnable starts!");
  4.                
  5.         }
  6.         public void run() {
  7.                 for(int i=0;i<300;i++) {
  8.                         try{Thread.sleep(1);}
  9.                         catch(Exception e){}
  10.                         System.out.println("Runnable");
  11.                 }
  12.         }
  13. }

  14. public class A extends Thread {
  15.         public A() {
  16.                 System.out.println("Thread Starts!");
  17.         }
  18.         public void run() {
  19.                 for(int i=0;i<300;i++) {
  20.                         try{Thread.sleep(1);}
  21.                         catch(Exception e){}
  22.                         System.out.println("Thread");
  23.                 }
  24.         }
  25.         public static void main(String[] args) {
  26.                 new Thread(new S()).start();
  27.                
  28.                 new A().start();
  29.         }
  30. }
复制代码
现在CPU速度太快了,循环数量少就很难看到,中间还都加了一条sleep语句来等待另一个线程去执行。
[ 本帖最后由 ccxztian 于 2011-08-05  11:29 编辑 ]
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马