黑马程序员技术交流社区
标题:
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
要看效果的话把你的代码加了几句:
class S implements Runnable {
public S() {
System.out.println("Runnable starts!");
}
public void run() {
for(int i=0;i<300;i++) {
try{Thread.sleep(1);}
catch(Exception e){}
System.out.println("Runnable");
}
}
}
public class A extends Thread {
public A() {
System.out.println("Thread Starts!");
}
public void run() {
for(int i=0;i<300;i++) {
try{Thread.sleep(1);}
catch(Exception e){}
System.out.println("Thread");
}
}
public static void main(String[] args) {
new Thread(new S()).start();
new A().start();
}
}
复制代码
现在CPU速度太快了,循环数量少就很难看到,中间还都加了一条sleep语句来等待另一个线程去执行。
[
本帖最后由 ccxztian 于 2011-08-05 11:29 编辑
]
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2