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



《Java程序设计教程 冶金工业出版社第9章》由会员分享,可在线阅读,更多相关《Java程序设计教程 冶金工业出版社第9章(9页珍藏版)》请在装配图网上搜索。
1、第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 ();
2、 }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.p
3、rintln ("the latest PI = "+this.latestPiEstimate ); }catch(InterruptedException e){ System.out.println("The caculator is Interrupted."); } } /**用于计算圆周率的方法,accuracy为计算精度*/ private void calPi(double accuracy) throws InterruptedException { this.latest
4、PiEstimate =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.latestPiEstim
5、ate += (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 T
6、hread(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{
7、 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 clas
8、s 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 (); } } c
9、lass 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.printStackTr
10、ace(); } 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[] a
11、rgs){ //创建新线程 CustomThread ct1 = new CustomThread(0); CustomThread ct2 = new CustomThread(1); //启动新线程 ct1.start (); ct2.start (); //输出main线程信息 for(int i = 0; i < 5; i++){ System.out.println("main thread: "+i); } System.out.println ("main thread has done!"
12、); } } class CustomThread extends Thread{ int id; public CustomThread(int customThreadID){ this.id = customThreadID; } //重定义子线程的run()方法 public void run(){ //输出自定义线程的信息 for(int i = 0; i < 5; i++){ System.out.println ("CustomThread #"+ this.id +": "+i); } S
13、ystem.out.println ("CustomThread #"+this.id+" has done!"); } } //例程9-5:DigitalClock.java /*采用多线程技术演示一个简单的数字时钟*/ import java.awt.event.*; import java.awt.*; import javax.swing.*; public class DigitalClock extends JFrame{ public static void main(String[] args) { JFrame frame =
14、new DigitalClock(); frame.show(); } public DigitalClock(){ this.setSize(200,150); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //数字时钟面板 final ClockPane cp = new ClockPane(); //设置按钮状态并注册事件监听者 final JButton start = new JButton("start");
15、 final JButton stop = new JButton("stop"); stop.setEnabled(false); start.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ cp.startClock(); start.setEnabled(false); stop.setEnabled(true);
16、 } }); stop.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ cp.stopClock (); start.setEnabled(true); stop.setEnabled(false); } }); //设置面板布局 JPanel buttomPan
17、e = new JPanel(); buttomPane.add(start); buttomPane.add(stop); JPanel contentPane = new JPanel(); contentPane.setLayout(new BorderLayout()); contentPane.add(cp,BorderLayout.CENTER); contentPane.add(buttomPane,BorderLayout.SOUTH); this.setContentPane(c
18、ontentPane); this.setResizable(false); } } //例程9-6:ClockPane.java /*数字时钟面板的实现类*/ import javax.swing.JPanel; import java.util.*; import java.awt.*; import java.awt.font.FontRenderContext; import java.awt.geom.*; import java.text.*; public class ClockPane extends JPanel implement
19、s Runnable { //线程是否中止的标志 boolean running = false; //用于显示当前时间的字符串 String time = "Clock"; Font font = new Font("SanSerif", Font.BOLD, 40); //启动报时器 public void startClock() { this.running = true; Thread t = new Thread(this); t.start(); } //终止报
20、时器 public void stopClock() { this.running = false; } //实现Runnable接口的run()方法 public void run() { while (this.running) { //获取当前时间并转换成字符串 this.time = DateFormat.getTimeInstance().format(new Date()); this.repaint();
21、//让当前线程休眠1秒钟 try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } //输出当前时间 public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g
22、2 = (Graphics2D) g; g2.setFont(this.font); FontRenderContext contex = g2.getFontRenderContext(); Rectangle2D bound = this.font.getStringBounds(this.time, contex); int strX = (int) ((this.getWidth() - bound.getWidth()) / 2); int strY = (int) ((this.getHeig
23、ht() - bound.getHeight()) / 2) + 40; g2.drawString(this.time, strX, strY); } } //例程9-7:IOPipeDemo.java /*演示采用管道机制的线程间通信*/ import java.io.*; public class IOPipeDemo{ public static void main(String[] args){ try{ //创建并连接管道 final PipedOutputStream pout = n
24、ew PipedOutputStream(); final PipedInputStream pin = new PipedInputStream(pout); //创建并启动输出线程 Thread outputThread = new Thread(new Runnable(){ public void run(){ writeBytes(pout); } }); outputThread.start(); //创建并启动输入线程
25、 Thread inputThread = new Thread(new Runnable(){ public void run(){ readBytes(pin); } }); inputThread.start(); }catch(IOException e){ e.printStackTrace(); } } //往管道中写入数据 public static void writeBytes(OutputStream o
26、utstream){ try{ DataOutputStream out = new DataOutputStream( new BufferedOutputStream(outstream) ); Thread t = Thread.currentThread (); for(int i=0; i<10; i++){ System.out.println ("write integer "+i+" to pipe."); out.writeInt(i);
27、 t.yield (); } out.flush(); out.close(); System.out.println ("Write data to pipe has done"); }catch(IOException e){ e.printStackTrace(); } } //从管道中读取数据 public static void readBytes(InputStream inputstream){ try{
28、 DataInputStream in = new DataInputStream( new BufferedInputStream(inputstream) ); Thread t = Thread.currentThread (); boolean eof = false; while(!eof){ try{ int i = in.readInt(); System.out.println("Read integer "+i+" from pipe
29、"); t.yield (); }catch(EOFException e){ eof = true; } } System.out.println ("Read data from pipe has done"); }catch(IOException e){ e.printStackTrace(); } } } //例程9-8 Hello_World.java import javax.swing.*; import java.awt.*; public class Hello_world extends JApplet{ public void paint(Graphics g){ g.drawString("Hello,world!",5,10); } } HelloWorld.html 代码
- 温馨提示:
1: 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
2: 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
3.本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
5. 装配图网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。