文档详情

Java语言程序设计第八章节.ppt

发布:2017-04-30约7.95千字共45页下载文档
文本预览下载声明
第8章 线程;本讲内容;线程的概念;Thread类简介;例8_1 在新线程中计算整数的阶乘;// class FactorialThread controls thread execution class FactorialThread extends Thread { 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); } } ;运行结果如下: main thread starts new thread started,main thread ends The factorial of 10 is 3628800 new thread ends ;例8_2 创建3个新线程,每个线程睡眠任意0-6秒钟,然后结束。;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 ); //线程休眠 } catch ( InterruptedException exception ) {}; //运行结束,给出提示信息 System.out.println( getName() + finished ); } };运行结果为: 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;Runnable接口;例8_3 使用Runnable接口实现例8_1功能;// class FactorialThread controls thread execution 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); } } ;例8_4 使用Runnable接口实现例8_2功能;cl
显示全部
相似文档