Topic: 有如下多线程程序,问有没有可能? |
Print this page |
1.有如下多线程程序,问有没有可能? | Copy to clipboard |
Posted by: colo007 Posted on: 2004-12-16 20:59 原代码如下: public class ThreadDemo extends Thread { String threadName; public ThreadDemo(String s) { System.out.println(" Making thread:" + s); threadName=s; } public void run() { for(int i=0; i<3; i++) { System.out.println(" Running thread number=" + threadName); try { Thread.sleep((int)(Math.random() * 1000)); } catch ( InterruptedException ex ) { System.err.println(ex.toString()); } } } public static void main(String[] args) { String download = "downloading"; String play = "playing"; ThreadDemo downloadThread, playThread; downloadThread = new ThreadDemo(download); playThread = new ThreadDemo(play); downloadThread.start(); playThread.start(); System.out.println("End of main"); } } ====================================== 出现如下的结果: Making thread:downloading Making thread:playing End of main Running thread number=downloading Running thread number=playing Running thread number=downloading Running thread number=playing Running thread number=playing Running thread number=downloading ====================================== 我是在书上面看到的,但是总是觉得End of main不会在线程Running前打印出来。至少打印几个Running再End of main。但是实际确相反,不知道是为什么? |
2.Re:有如下多线程程序,问有没有可能? [Re: colo007] | Copy to clipboard |
Posted by: jimmywin Posted on: 2004-12-17 09:59 为什么不会呢? 怎么说呢,我是这么理解的,当你调用线程的start()以后,你可以认为它就暂时独立于main函数之外了,这个时候,你的downloadThread、playThread、main的执行就依赖于排程器了。从打印的结果看,排程器是先分派给了main,然后是downloadThread、接着它又选择了playThread… 就是说当你start()一个线程后,并不意味着这个线程马上就执行,它的执行与否,依赖于系统排程器的选择。 |
3.Re:有如下多线程程序,问有没有可能? [Re: colo007] | Copy to clipboard |
Posted by: colo007 Posted on: 2004-12-17 12:54 是不是可以这样理解:用上了多线程的时候,程序就不单纯是从上往下运行了,运行顺序取决于系统调配上。是吗? |
4.Re:有如下多线程程序,问有没有可能? [Re: colo007] | Copy to clipboard |
Posted by: jimmywin Posted on: 2004-12-17 13:48 可以认为从你在main里调用一个线程的start()方法起,该线程就和你的 main 并行执行了。至于具体的谁先谁后,则取决于排程器,当然指定线程的优先级也能影响到线程的执行次序。 就拿你的例子来说,执行完 downloadThread.start() 以后,downloadThread 这个线程就去干它该干的事去了,从这一刻起可以认为它和你的 main 函数就站在同一起跑线上了,至于谁跑在前面,就看排程器让谁先跑了。 |
5.Re:有如下多线程程序,问有没有可能? [Re: colo007] | Copy to clipboard |
Posted by: colo007 Posted on: 2004-12-17 15:13 完全明白了,谢谢 |
6.Re:有如下多线程程序,问有没有可能? [Re: colo007] | Copy to clipboard |
Posted by: fanrenII Posted on: 2004-12-23 14:09 This depends on the thread modle that your program sticks to. Your program is using the aggresive mode. So you got the result presented above. |
Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1 客服电话 18559299278 客服信箱 714923@qq.com 客服QQ 714923 |