读书人

多线程求教!解决办法

发布时间: 2012-01-01 23:10:55 作者: rapoo

多线程求教!
我拷贝了 《java 2 参考大全》上的一段源代码,我对其中的运行不是很理解,现在先把程序列在下面。

public class NewThread implements Runnable{

Thread t;

NewThread(){
t = new Thread(this, "Demo Thread ");
System.out.println( "child thread: "+ t);
t.start();
}

public void run(){
try{
for(int i=5;i> 0;i--)
{
System.out.println( "child Thread: "+i);
Thread.sleep(500);

}

}catch(InterruptedException e){

System.out.println( "child thread interrupted ");

}
System.out.println( "child thread exited ");
}
}


主程序如下:
public class ThreadDemo {

/**
* @method_name main
* @author xddiao@cattsoft.com
* @date 2007-6-14 下午02:55:59
* @description
* @param args
* @reviewed_by
*/
public static void main(String[] args) {
// TODO 自动生成方法存根
new NewThread();
try{
for(int i=5;i> 0;i--)
{
System.out.println( "main thread: "+i);
Thread.sleep(1000);
}
}catch(InterruptedException e){
System.out.println( "main thread interrupted. ");

}
System.out.println( "main thread exited! ");

}

}


这个程序的执行结果如下:
child thread: Thread[Demo Thread,5,main]
main thread:5
child Thread: 5
child Thread: 4
main thread:4
child Thread: 3
child Thread: 2
main thread:3
child Thread: 1
child thread exited
main thread:2
main thread:1
main thread exited!

我不明白的地方是:
为何子线程在输出child thread: Thread[Demo Thread,5,main] 之后,就马上切换回主线程呢 ?t.start()不是调用了t.run()吗,为何不等到t.run()执行完毕才执行主线程呢?这是什么原因?这个切换是怎么规定的呢?
我略微写一下思路:
start(){
this.run();
}

这个问得比较深了, 运行时,凭什么不把start后大括号内的程序运行完才跳出start呢, 这个是怎么实现的?不能说就是线程机制,到底线程机制是怎么实现的呢?
先在这里谢过各位的解答! 等待中。。。。


[解决办法]
就是因为项达到分开运行的效果才要线呈的。

这就是线程的目的。

怎么实现的应该问sun去。外部程序实现的
[解决办法]
线程就是并发
JAVA的线程是抢占式的
如果你把this.start()改成this.run()的话,那就意味着此时不是开启一个线程,而是对run()方法的一个调用

[解决办法]
start()不是直接调用run()的,而是启动一个线程,然后在线程里运行run()作为线程的执行体。这个输出不是一定的,多运行几次,会有不同的结果。
Thread.sleep()会使线程睡眠,从而交出CPU使用权,如果某个线程一直不使用sleep()……后果比较严重,jvm会很难找到把CPU使用权交给其他线程的机会。

读书人网 >J2SE开发

热点推荐