Java程序设计教程 冶金工业出版社第9章.doc
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- Java程序设计教程 冶金工业出版社第9章 Java 程序设计 教程 冶金工业 出版社
- 资源描述:
-
第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 = "+this.latestPiEstimate );
}catch(InterruptedException e){
System.out.println("The caculator is Interrupted.");
}
}
/**用于计算圆周率的方法,accuracy为计算精度*/
private void calPi(double accuracy) throws InterruptedException
{
this.latestPiEstimate =0.0;
long iteration = 0;
int sign = -1;
//按给定精度计算圆周率
while(Math.abs (Math.PI-this.latestPiEstimate)>accuracy){
if(Thread.interrupted ())
throw new InterruptedException();
iteration++;
sign = -sign;
this.latestPiEstimate += (sign*4.0/(2*iteration-1));
}
}
}
//例程9-2:SynDemo.java
/*演示没有进行线程同步所带来的问题*/
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");
t1.start();
t2.start();
}
}
class Demostrator implements Runnable{
private int shareData = 0;
public void run(){
Thread t = Thread.currentThread ();
for(int i = 1; i <= 5; i++){
int copy = shareData;
try{
Thread.sleep ((int)(Math.random ()*1000));
}catch(Exception e){
e.printStackTrace();
}
System.out.println ("Thread "+t.getName ()+": copy="+copy
+"\tshareData="+shareData);
shareData++;
}
}
}
//例程9-3:DeadLockDemo.java
public class DeadLockDemo{
public static void main(String[] args){
DemoObject a = new DemoObject();
DemoObject b = new DemoObject();
a.another = b;
b.another = a;
Thread t1 = new Thread(a,"t1");
Thread t2 = new Thread(b,"t2");
t1.start ();
t2.start ();
}
}
class DemoObject implements Runnable{
public DemoObject another = null;
public void run(){
this.method ();
}
public synchronized void method(){
if(this.another != null){
try{
Thread.sleep (1000);
}catch(Exception e){
e.printStackTrace();
}
another.method ();
//下面的代码段实际上是执行不到的
System.out.println ("If you can see this line,no
deadlock happened");
}
}
}
//例程9-4: ThreeThreadDemo.java
/*ThreeThreadDemo.java*/
public class ThreeThreadDemo{
public static void main(String[] args){
//创建新线程
CustomThread ct1 = new CustomThread(0);
展开阅读全文
文档分享网所有资源均是用户自行上传分享,仅供网友学习交流,未经上传用户书面授权,请勿作他用。
相关资源
更多
相关搜索



链接地址:https://www.wdfxw.net/doc37516614.htm