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



《Java程序設(shè)計(jì)教程 冶金工業(yè)出版社第9章》由會(huì)員分享,可在線閱讀,更多相關(guān)《Java程序設(shè)計(jì)教程 冶金工業(yè)出版社第9章(9頁(yè)珍藏版)》請(qǐng)?jiān)谘b配圖網(wǎng)上搜索。
1、第9章 多線程與Applet //例程9-1:Pi.java /*演示采用多線程技術(shù)計(jì)算圓周率*/ 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);
3、 System.out.println ("the latest PI = "+this.latestPiEstimate ); }catch(InterruptedException e){ System.out.println("The caculator is Interrupted."); } } /**用于計(jì)算圓周率的方法,accuracy為計(jì)算精度*/ private void calPi(double accuracy) throws Int
4、erruptedException { this.latestPiEstimate =0.0; long iteration = 0; int sign = -1; //按給定精度計(jì)算圓周率 while(Math.abs (Math.PI-this.latestPiEstimate)>accuracy){ if(Thread.interrupted ()) throw new InterruptedException(); iteration++;
5、 sign = -sign; this.latestPiEstimate += (sign*4.0/(2*iteration-1)); } } } //例程9-2:SynDemo.java /*演示沒(méi)有進(jìn)行線程同步所帶來(lái)的問(wèn)題*/ public class SynDemo{ public static void main(String[] args){ Demostrator shareDemostrator = new Demostrator(); Thread t1 = new Thread(shar
6、eDemostrator,"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 =
7、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=&qu
8、ot;+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
9、(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(
10、this.another != null){ try{ Thread.sleep (1000); }catch(Exception e){ e.printStackTrace(); } another.method (); //下面的代碼段實(shí)際上是執(zhí)行不到的 System.out.println ("If you can see this line,no deadlock happened"); } } }
11、 //例程9-4: ThreeThreadDemo.java /*ThreeThreadDemo.java*/ public class ThreeThreadDemo{ public static void main(String[] args){ //創(chuàng)建新線程 CustomThread ct1 = new CustomThread(0); CustomThread ct2 = new CustomThread(1); //啟動(dòng)新線程 ct1.start (); ct2.start (); //輸出main線程信息
12、 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; } //重定義子線程的ru
13、n()方法 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 /*采用多線程技術(shù)演示一個(gè)
14、簡(jiǎn)單的數(shù)字時(shí)鐘*/ 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);
15、 this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //數(shù)字時(shí)鐘面板 final ClockPane cp = new ClockPane(); //設(shè)置按鈕狀態(tài)并注冊(cè)事件監(jiān)聽(tīng)者 final JButton start = new JButton("start"); final JButton stop = new JButton("stop"); stop.setEnabled(false);
16、start.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ cp.startClock(); start.setEnabled(false); stop.setEnabled(true); } }); stop.addActionListener(new ActionListener(){ pu
17、blic void actionPerformed(ActionEvent e){ cp.stopClock (); start.setEnabled(true); stop.setEnabled(false); } }); //設(shè)置面板布局 JPanel buttomPane = new JPanel(); buttomPane.add(start); buttomPane.add(stop); JPan
18、el 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 /*數(shù)字時(shí)鐘面
19、板的實(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 implements Runnable { //線程是否中止的標(biāo)志 boolean running = false; //用于顯示當(dāng)前時(shí)間的字符串 String ti
20、me = "Clock"; Font font = new Font("SanSerif", Font.BOLD, 40); //啟動(dòng)報(bào)時(shí)器 public void startClock() { this.running = true; Thread t = new Thread(this); t.start(); } //終止報(bào)時(shí)器 public void stopClock() { this.running = false;
21、 } //實(shí)現(xiàn)Runnable接口的run()方法 public void run() { while (this.running) { //獲取當(dāng)前時(shí)間并轉(zhuǎn)換成字符串 this.time = DateFormat.getTimeInstance().format(new Date()); this.repaint(); //讓當(dāng)前線程休眠1秒鐘 try { Thread.sleep(1000);
22、 } catch (InterruptedException e) { e.printStackTrace(); } } } //輸出當(dāng)前時(shí)間 public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; g2.setFont(this.font); FontRen
23、derContext 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.tim
24、e, strX, strY); } } //例程9-7:IOPipeDemo.java /*演示采用管道機(jī)制的線程間通信*/ import java.io.*; public class IOPipeDemo{ public static void main(String[] args){ try{ //創(chuàng)建并連接管道 final PipedOutputStream pout = new PipedOutputStream(); final PipedInputStream pin = new Pip
25、edInputStream(pout); //創(chuàng)建并啟動(dòng)輸出線程 Thread outputThread = new Thread(new Runnable(){ public void run(){ writeBytes(pout); } }); outputThread.start(); //創(chuàng)建并啟動(dòng)輸入線程 Thread inputThread = new Thread(new Runnable(){ public v
26、oid run(){ readBytes(pin); } }); inputThread.start(); }catch(IOException e){ e.printStackTrace(); } } //往管道中寫(xiě)入數(shù)據(jù) public static void writeBytes(OutputStream outstream){ try{ DataOutputStream out = new DataOutput
27、Stream( 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(
28、); 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{ DataInputStream in = new DataInp
29、utStream( 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
30、.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
31、.awt.*; public class Hello_world extends JApplet{ public void paint(Graphics g){ g.drawString("Hello,world!",5,10); } } HelloWorld.html 代碼 <HTML> <HEAD><TITLE>HELLO,WORLD!</TITLE></HEAD> <BODY> <APPLET code="Hello_World.class" width=300 height=300></APPLET> </BODY> </HTML>
- 溫馨提示:
1: 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
2: 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
3.本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
5. 裝配圖網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 踏春尋趣 樂(lè)享時(shí)光——春季旅游踏春出游活動(dòng)
- 清明假期至安全不缺席風(fēng)起正清明安全需守護(hù)
- 全國(guó)黨員教育培訓(xùn)工作規(guī)劃
- XX中小學(xué)公共衛(wèi)生培訓(xùn)樹(shù)立文明衛(wèi)生意識(shí)養(yǎng)成良好衛(wèi)生習(xí)慣
- 小學(xué)生常見(jiàn)傳染病預(yù)防知識(shí)培訓(xùn)傳染病的預(yù)防措施
- 3月18日全國(guó)愛(ài)肝日中西醫(yī)結(jié)合逆轉(zhuǎn)肝硬化
- 肝病健康宣教守護(hù)您的肝臟健康如何預(yù)防肝炎
- 垃圾分類小課堂教育綠色小衛(wèi)士分類大行動(dòng)
- 中小學(xué)班主任經(jīng)驗(yàn)交流從勝任到優(yōu)秀身為世范為人師表 立責(zé)于心履責(zé)于行
- 教師數(shù)字化轉(zhuǎn)型理解與感悟教師數(shù)字化轉(zhuǎn)型的策略與建議
- 團(tuán)建小游戲團(tuán)建破冰小游戲團(tuán)隊(duì)協(xié)作破冰游戲多人互動(dòng)
- 教師使用deepseek使用攻略讓備課效能提升
- 辦公室會(huì)議紀(jì)要培訓(xùn)會(huì)議內(nèi)容會(huì)議整理公文攥寫(xiě)
- 黨員要注重培塑忠誠(chéng)奮斗奉獻(xiàn)的人格力量
- 橙色卡通風(fēng)兒童春季趣味運(yùn)動(dòng)會(huì)
相關(guān)資源
更多