线程与对象群体的组织ppt课件.ppt

  1. 1、有哪些信誉好的足球投注网站(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。。
  2. 2、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载
  3. 3、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
线程与对象群体的组织ppt课件

第七章 线程与对象群体的组织;目录;7.1 多线程编程基础;7.1.1 线程的概念;线程 一个程序中多段代码同时并发执行,称为多线程 通过多线程,一个进程表面上看同时可以执行一个以上的任务——并发 创建线程比创建进程开销要小得多,线程之间的协作和数据交换也比较容易 Java是第一个支持内置线程操作的主流编程语言 多数程序设计语言支持多线程要借助于操作系统“原语(primitives)”;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();public final void setPriority( int newPriority);创建3个新线程,每个线程睡眠一段时间(0~6秒),然后结束 public class Ex7_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.start(); // 启动线程3 System.out.println( Threads started, main ends\n ); } };class TestThread extends Thread { private int sleepTime; public TestThread( String name ) { super( name ); sleepTime = ( int ) ( Math.random() * 6000 ); } public void run() { try { System.out.println( getName() + going to sleep for + sleepTime ); Thread.sleep( sleepTime

文档评论(0)

gz2018gz + 关注
实名认证
内容提供者

该用户很懒,什么也没介绍

1亿VIP精品文档

相关文档