- 1、本文档共67页,可阅读全部内容。
- 2、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。
- 3、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载。
- 4、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
- 5、该文档为VIP文档,如果想要下载,成为VIP会员后,下载免费。
- 6、成为VIP后,下载本文档将扣除1次下载权益。下载后,不支持退款、换文档。如有疑问请联系我们。
- 7、成为VIP后,您将拥有八大权益,权益包括:VIP文档下载权益、阅读免打扰、文档格式转换、高级专利检索、专属身份标志、高级客服、多端互通、版权登记。
- 8、VIP文档为合作方或网友上传,每下载1次, 网站将根据用户上传文档的质量评分、类型等,对文档贡献者给予高额补贴、流量扶持。如果你也想贡献VIP文档。上传文档
查看更多
java语言程序设计[第3版,清华]第8章new
第九章 线程;目录;线程的概念;线程
一个程序中多段代码同时并发执行,称为多线程
通过多线程,一个进程表面上看同时可以执行一个以上的任务——并发
创建线程比创建进程开销要小得多,线程之间的协作和数据交换也比较容易(进程独站资源)
线程间共享资源(内存、代码、数据)有利于并行处理;线程的状态与生命周期;Life Cycle of Thread;诞生状态
线程刚刚被创建
就绪状态
线程的 start 方法已被执行
线程已准备好运行
运行状态
处理机分配给了线程,线程正在运行
阻塞状态(Blocked)
在线程发出输入/输出请求且必须等待其返回
遇到用synchronized标记的方法而未获得其监视器暂时不能进入执行时
休眠状态(Sleeping)
执行sleep方法而进入休眠
死亡状态
线程已完成或退出;;;Thread类;public class Example9_1
{ public static void main(String args[])
{ Lefthand left;
Righthand right;
left=new Lefthand() ; //创建线程
right=new Righthand();
left.start();
right.start();
for(int i=1;i=3;i++)
{ System.out.println(我是主线程);
}
}
};Thread类(续);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方法返回就继续运行(执行System.out.println()),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线程才结束
例子 Ex8_1.java
;Thread类(续) ——常用API函数;public void start();public final void setPriority(
int newPriority);创建3个新线程,每个线程睡眠一段时间(0~6秒),然后结束
public class Ex8_2 {
public static void main( String [] args ) {
//创建并命名每个线程
TestThread thread1 = new TestThread( thread1 );
TestThread thread2 = new TestThread( thread2 );
TestThread thread3 = new TestThread( thread3 );
System.out.println( Starting threads );
thread1.start(); // 启动线程1
thread2.start(); // 启动线程2
thread3.
文档评论(0)