


编号:时间:2021年x月x日书山有路勤为径,学海无涯苦作舟页码:第9页 共9页第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.javapublic 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); 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!"); }}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); } System.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 = 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"); 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); } }); stop.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ cp.stopClock (); start.setEnabled(true); stop.setEnabled(false); } }); //设置面板布局 JPanel buttomPane = 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(contentPane); 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 implements 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(); } //终止报时器 public void stopClock() { this.running = false; } //实现Runnable接口的run()方法 public void run() { while (this.running) { //获取当前时间并转换成字符串 this.time = DateFormat.getTimeInstance().format(new Date()); this.repaint(); //让当前线程休眠1秒钟 try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } //输出当前时间 public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (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.getHeight() - 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 = new PipedOutputStream(); final PipedInputStream pin = new PipedInputStream(pout); //创建并启动输出线程 Thread outputThread = new Thread(new Runnable(){ public void run(){ writeBytes(pout); } }); outputThread.start(); //创建并启动输入线程 Thread inputThread = new Thread(new Runnable(){ public void run(){ readBytes(pin); } }); inputThread.start(); }catch(IOException e){ e.printStackTrace(); } } //往管道中写入数据 public static void writeBytes(OutputStream outstream){ 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); 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{ 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"); 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.javaimport javax.swing.*;import java.awt.*;public class Hello_world extends JApplet{public void paint(Graphics g){g.drawString("Hello,world!",5,10);}}HelloWorld.html 代码