1 / 9
文档名称:

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

格式:doc   大小:76KB   页数:9页
下载后只包含 1 个 DOC 格式的文档,没有任何的图纸或源代码,查看文件列表

如果您已付费下载过本站文档,您可以点这里二次下载

分享

预览

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

上传人:xxj16588 2018/1/4 文件大小:76 KB

下载得到文件列表

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

文档介绍

文档介绍:第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