- 1、有哪些信誉好的足球投注网站(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。。
- 2、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载。
- 3、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
第七章 线程与对象群体的组织;目录;7.1.2 Thread类;7.1.2 Thread类(续) ——例7_1;public void run() {
int i=num;
int result=1;
System.out.println(new thread started );
while(i0) {
result=result*i;
i=i-1;
}
System.out.println(The factorial of +num+ is +result);
System.out.println(new thread ends);
}
}
运行结果
main thread starts
main thread ends
new thread started
The factorial of 10 is 3628800
new thread ends
;结果说明
main线程已经执行完后,新线程才执行完
main函数调用thread.start()方法启动新线程后并不等待其run方法返回就继续运行,thread.run函数在一边独自运行,不影响原来的main函数的运行
源程序修改
如果启动新线程后希望主线程多持续一会再结束,可在start语句后加上让当前线程(这里当然是main)休息1毫秒的语句:
try { Thread.sleep(1); } catch(Exception e){};;修改后运行结果
main thread starts
new thread stared
The factorial of 10 is 3628800
new thread ends
main thread ends
运行结果说明
新线程结束后main线程才结束
;7.1.2 Thread类(续) ——常用API函数;public void start();运行结果
Starting threads
Threads started, main ends
thread1 going to sleep for 3519
thread2 going to sleep for 1689
thread3 going to sleep for 5565
thread2 finished
thread1 finished
thread3 finished
说明
由于线程3休眠时间最长,所以最后结束,线程2休眠时间最短,所以最先结束
每次运行,都会产生不同的随机休眠时间,所以结果都不相同;7.1.3 Runnable接口;使用Runnable接口实现例7_1功能
public class Ex7_1{
public static void main( String [] args ) {
System.out.println(main thread starts);
FactorialThread t=new FactorialThread(10);
new Thread(t).start();
System.out.println(new thread started,main thread ends );
}
} ;class FactorialThread implements Runnable {
private int num;
public FactorialThread( int num ) {
this.num=num;
}
public void run() {
int i=num;
int result=1;
while(i0) {
result=result*i;
i=i-1;
}
System.out.println(The factorial of +num+ is +result);
System.out.println(new thread ends);
}
}
;使用Runnable接口实现例7_2功能
public class Ex7_4{
public static void main( String [] args ) {
TestThread thread1 = new TestThread();
TestThread thread2
您可能关注的文档
- ConfiguringandVerifyingRouteRedistribution文件材料.ppt
- ConfiguringCiscoEasyVPNandEasyVPNServerUsingSDM文件材料.ppt
- ConfiguringCiscoIOSIPS文件材料教学稿件.ppt
- ConfiguringLayerRedundancywithVRRPandGLBP文件材料.ppt
- ConfiguringLinkAggregationwithEtherChannel文件材料.ppt
- ConfiguringOSPFRouting文件材料.ppt
- ConfiguringWFQ文件材料教学稿件.ppt
- COPD定义发病机理分级及诊断文件材料.ppt
- copd防治指南文件材料教学稿件.ppt
- copd护理查房(二)文件材料教学稿件.ppt
文档评论(0)