黑马程序员技术交流社区

标题: java 多线程的疑惑 [打印本页]

作者: 张扬    时间: 2011-8-5 10:08
标题: java 多线程的疑惑
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
作者: 匿名    时间: 2011-8-5 11:07
标题: 回复 楼主 的帖子
用张老师说的话就是  我抢了篮球还可以去接着抢,并不是这次我抢了下次就给你抢。
作者: ccxztian    时间: 2011-8-5 11:27
要看效果的话把你的代码加了几句:
  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 编辑 ]




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2