第9章多线程与Applet
//例程9-1:Pi.java
/*演示采用多线程技术计算圆周率*/
public class Pi{
public static void main(String[] args){
PiCaculator pc = new PiCaculator();
Thread t = new Thread(pc);
t.start();
try{
Thread.sleep (10000); //休眠,等待可能出现的异常情况
t.interrupt ();
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
class PiCaculator implements Runnable{
private double latestPiEstimate;
public void run(){
try{
System.out.print ("Math.PI = "+ Math.PI + "\t" );
calPi(0.00001);
System.out.println ("the latest PI = "+http://www.doczj.com/doc/c5af6d3410661ed9ad51f381.htmltestPiEstimate );
}catch(InterruptedException e){
System.out.println("The caculator is Interrupted.");
}
}
/**用于计算圆周率的方法,accuracy为计算精度*/
private void calPi(double accuracy) throws InterruptedException
{
http://www.doczj.com/doc/c5af6d3410661ed9ad51f381.htmltestPiEstimate =0.0;
long iteration = 0;
int sign = -1;
//按给定精度计算圆周率
while(Math.abs (http://www.doczj.com/doc/c5af6d3410661ed9ad51f381.htmltestPiEstimate)>accuracy){
if(Thread.interrupted ())
throw new InterruptedException();