帮忙看下线程问题

xuqq 2004-08-09 10:19:08
执行过程是怎样的
t1.start();会如何引导程序
run是怎样被调用的

谢谢

程序如下:
public class Thread2 implements Runnable {
int threadNumber;
public Thread2(int i) {
System.out.println(" Making thread=" + i);
threadNumber=i;
}
public void run() {
for(int i=0; i<3; i++) {
System.out.println(" Running thread number=" + threadNumber);
try {
Thread.sleep((int)(Math.random() * 1000));
}
catch ( InterruptedException ex ) {
System.err.println(ex.toString());
}
}
}
public static void main(String[] args) {
Thread t1, t2;
t1=new Thread(new Thread2(1));
t1.start();
t2=new Thread(new Thread2(2));
t2.start();
System.out.println(" End of main");
}
}
...全文
99 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
mingjava 2004-08-09
  • 打赏
  • 举报
回复
首先你的Thread2是继承了Runnable接口并实现了它的方法run()的,因此你要是想让这个Runnable的对象在线程运行起来你必须要Thread t = new Thread(Runnable obj);t.start()这样来调用。如果你的Thread2是继承Thread并覆盖它的run()方法的话,那么你就可以
Thread2 t = new Thread2(xxx) t.start()了,总之你调用start()才能让线程处于Ready状态,至于它什么时候运行是虚拟机调度的,程序不能干预。现在你应该清楚start()并不表示线程立刻运行了。
其次线程开始运行后,就去执行run()中的代码,你程序中的代码比较简单,因此它执行完一次System.out.println()后就暂停你指定的时间然后继续执行下次循环,直到run()的方法执行完毕,线程就结束了。你的主线程在main()执行完后就结束了。等你的t1,t2结束后,虚拟机发现没有deamon的线程了那么你的应用程序就会结束。
xuqq 2004-08-09
  • 打赏
  • 举报
回复
结果输出为Making Thread=1;
Making Thread=2;
End of main;
Running thread num=1;
Running thread num=2;
Running thread num=1;
Running thread num=2;
Running thread num=1;
Running thread num=1;
那么是不是因为 执行t1.start();后就调用了t1的run函数,然后t1就sleep 去了,这样就跳出了那个for循环啊?
然后t2 new 出来,也去调用run 了,这个时候t1还没醒过来,t2进行run函数后也去sleep了,这个时候t1,t2都没醒过来。
于是执行下一句,显示End of main。

然后呢?t1醒过来,继续没有完成的for语句?



sleep()完了谁唤醒它的呢?
是不是最后"Running thread number="这句话出现6次,且1,2各随机的出现3次?

谢谢。请一一指教。好吗?以上。给50分
hl_longman 2004-08-09
  • 打赏
  • 举报
回复
public void start()
Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.
The result is that two threads are running concurrently: the current thread (which returns from the call to the start method) and the other thread (which executes its run method).


lightsword 2004-08-09
  • 打赏
  • 举报
回复
是呀同时启动,不过记住两个线程执行时,不是一个一个交替的,而是不一定先执行哪个线程.....
draco2002 2004-08-09
  • 打赏
  • 举报
回复
你每次执行t1.start();则系统自动调用对应的run方法来运行线程。

在上面的程序中你启动了两个线程:t1.start()和t2.start()
TinyJimmy 2004-08-09
  • 打赏
  • 举报
回复
run是由虚拟机调用的
xuqq 2004-08-09
  • 打赏
  • 举报
回复
我给分了,居然这里显示为0?????

62,623

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧