Java程序設計教程 冶金工業(yè)出版社第9章



《Java程序設計教程 冶金工業(yè)出版社第9章》由會員分享,可在線閱讀,更多相關《Java程序設計教程 冶金工業(yè)出版社第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); //休眠,等待可能出現(xiàn)的異常情況 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 (); //下面的代碼段實際上是執(zhí)行不到的 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){ //創(chuàng)建新線程 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 /*采用多線程技術演示一個簡單的數(shù)字時鐘*/ 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); //數(shù)字時鐘面板 final ClockPane cp = new ClockPane(); //設置按鈕狀態(tài)并注冊事件監(jiān)聽者 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 /*數(shù)字時鐘面板的實現(xiàn)類*/ 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; } //實現(xiàn)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{ //創(chuàng)建并連接管道 final PipedOutputStream pout = n
24、ew PipedOutputStream(); final PipedInputStream pin = new PipedInputStream(pout); //創(chuàng)建并啟動輸出線程 Thread outputThread = new Thread(new Runnable(){ public void run(){ writeBytes(pout); } }); outputThread.start(); //創(chuàng)建并啟動輸入線程
25、 Thread inputThread = new Thread(new Runnable(){ public void run(){ readBytes(pin); } }); inputThread.start(); }catch(IOException e){ e.printStackTrace(); } } //往管道中寫入數(shù)據(jù) 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(); } } //從管道中讀取數(shù)據(jù) 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: 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權益歸上傳用戶所有。
3.本站RAR壓縮包中若帶圖紙,網頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
4. 未經權益所有人同意不得將文件中的內容挪作商業(yè)或盈利用途。
5. 裝配圖網僅提供信息存儲空間,僅對用戶上傳內容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
6. 下載文件中如有侵權或不適當內容,請與我們聯(lián)系,我們立即糾正。
7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 2025年作風建設學習教育開展情況的報告范文
- 在2025年民營企業(yè)座談會上的主持講話范文
- 在2025年全縣教育領域群眾身邊不正之風和腐敗問題集中整治調度會上的講話范文
- 工委副書記在2025年機關DeepSeek應用專題輔導培訓班開班儀式上的講話范文
- 在2025年DeepSeek大模型政務應用培訓會上的講話范文
- 在青年干部培訓結業(yè)典禮上的講話文稿
- 2025年副書記防汛工作會議上的講話范文
- 2025年主管商務部門黨組書記在理論學習中心組會上研討發(fā)言文稿
- 2025年國企黨委關于干部職工思想政治工作情況的報告范文
- 在機關單位作風建設學習教育突出問題專項整治工作部署會議上的講話范文
- 醫(yī)院領導2025年黨風廉政建設推進會上的講話范文
- 2025年關于開展“以案促改”工作實施方案供參考
- 在2025年安全生產專項整治暨化工行業(yè)風險防控部署會上的講話范文
- 領導干部在“十五五”發(fā)展規(guī)劃編制啟動會上的講話文稿
- 2025年書記在慰問老干部暨情況通報會上的主持講話提綱范文