下载此文档

Java程序设计教程 冶金工业出版社第9章.doc


文档分类:IT计算机 | 页数:约9页 举报非法文档有奖
1/9
下载提示
  • 1.该资料是网友上传的,本站提供全文预览,预览什么样,下载就什么样。
  • 2.下载该文档所得收入归上传者、原创者。
  • 3.下载的文档,不会出现我们的网址水印。
1/9 下载此文档
文档列表 文档介绍
第9章多线程与Applet
//例程9-1:
/*演示采用多线程技术计算圆周率*/
public class Pi{
public static void main(String[] args){
PiCaculator pc = new PiCaculator();
Thread t = new Thread(pc);
();
try{
(10000); //休眠,等待可能出现的异常情况
();
}catch(InterruptedException e){
();
}
}
}
class PiCaculator implements Runnable{
private double latestPiEstimate;
public void run(){
try{
(" = "+ + "\t" );
calPi();
("the latest PI = "+ );
}catch(InterruptedException e){
("The caculator is Interrupted.");
}
}
/**用于计算圆周率的方法,accuracy为计算精度*/
private void calPi(double accuracy) throws InterruptedException
{
=;
long iteration = 0;
int sign = -1;
//按给定精度计算圆周率
while( (-)>accuracy){
if( ())
throw new InterruptedException();
iteration++;
sign = -sign;
+= (sign*/(2*iteration-1));
}
}
}
//例程9-2:
/*演示没有进行线程同步所带来的问题*/
public class SynDemo{
public static void main(String[] args){
Demostrator shareDemostrator = new Demostrator();
Thread t1 = new Thread(shareDemostrator,"t1");
Thread t2 = new Thread(shareDemostrator,"t2");
();
();
}
}
class Demostrator implements Runnable

Java程序设计教程 冶金工业出版社第9章 来自淘豆网www.taodocs.com转载请标明出处.

非法内容举报中心
文档信息
  • 页数9
  • 收藏数0 收藏
  • 顶次数0
  • 上传人xxj16588
  • 文件大小76 KB
  • 时间2018-01-04