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、編號(hào): 時(shí)間:2021年x月x日 書(shū)山有路勤為徑,學(xué)海無(wú)涯苦作舟 頁(yè)碼:第9頁(yè) 共9頁(yè) 第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 (100
2、00); //休眠,等待可能出現(xiàn)的異常情況 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 +
3、"\t" ); calPi(0.00001); 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
4、) throws InterruptedException { 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 Th
6、read(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;
7、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++;
8、} } } //例程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"
9、); 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);
10、 }catch(Exception e){ e.printStackTrace(); } another.method (); //下面的代碼段實(shí)際上是執(zhí)行不到的 System.out.println ("If you can see this line,no deadlock happened"); } } } //例程9-4: ThreeThreadDemo.java /*ThreeThreadDemo.java*/ public class Th
11、reeThreadDemo{ 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線程信息 for(int i = 0; i < 5; i++){ System.out.println("main thread: "+i);
12、 } 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.prin
13、tln ("CustomThread #"+ this.id +": "+i); } System.out.println ("CustomThread #"+this.id+" has done!"); } } //例程9-5:DigitalClock.java /*采用多線程技術(shù)演示一個(gè)簡(jiǎn)單的數(shù)字時(shí)鐘*/ import java.awt.event.*; import java.awt.*; import javax.swing.*; public class DigitalClock extends JFrame{ public static
14、 void main(String[] args) { JFrame frame = new DigitalClock(); frame.show(); } public DigitalClock(){ this.setSize(200,150); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //數(shù)字時(shí)鐘面板 final ClockPane cp = new ClockPane(); //設(shè)置按鈕狀態(tài)并注冊(cè)事件監(jiān)聽(tīng)
15、者 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.setEna
16、bled(false); stop.setEnabled(true); } }); stop.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ cp.stopClock (); start.setEnabled(true); stop.setEnabled(false);
17、 } }); //設(shè)置面板布局 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(buttomPa
18、ne,BorderLayout.SOUTH); this.setContentPane(contentPane); this.setResizable(false); } } //例程9-6:ClockPane.java /*數(shù)字時(shí)鐘面板的實(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
19、.*; public class ClockPane extends JPanel implements Runnable { //線程是否中止的標(biāo)志 boolean running = false; //用于顯示當(dāng)前時(shí)間的字符串 String time = "Clock"; Font font = new Font("SanSerif", Font.BOLD, 40); //啟動(dòng)報(bào)時(shí)器 public void startClock() { this.running = true; Thread t =
20、new Thread(this); t.start(); } //終止報(bào)時(shí)器 public void stopClock() { this.running = false; } //實(shí)現(xiàn)Runnable接口的run()方法 public void run() { while (this.running) { //獲取當(dāng)前時(shí)間并轉(zhuǎn)換成字符串 this.time = DateFormat.getTimeInstance().format(new
21、 Date()); this.repaint(); //讓當(dāng)前線程休眠1秒鐘 try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } //輸出當(dāng)前時(shí)間 public void paintComponent(Graphics g) {
22、 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.getWid
23、th()) / 2); int strY = (int) ((this.getHeight() - bound.getHeight()) / 2) + 40; g2.drawString(this.time, strX, strY); } } //例程9-7:IOPipeDemo.java /*演示采用管道機(jī)制的線程間通信*/ import java.io.*; public class IOPipeDemo{ public static void main(String[] args){ try{
24、 //創(chuàng)建并連接管道 final PipedOutputStream pout = new PipedOutputStream(); final PipedInputStream pin = new PipedInputStream(pout); //創(chuàng)建并啟動(dòng)輸出線程 Thread outputThread = new Thread(new Runnable(){ public void run(){ writeBytes(pout); } });
25、 outputThread.start(); //創(chuàng)建并啟動(dòng)輸入線程 Thread inputThread = new Thread(new Runnable(){ public void run(){ readBytes(pin); } }); inputThread.start(); }catch(IOException e){ e.printStackTrace(); } } //往管道中寫(xiě)入數(shù)
26、據(jù) 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 inte
27、ger "+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(); } } //從管道中讀取數(shù)據(jù) public static void r
28、eadBytes(InputStream inputstream){ try{ DataInputStream in = new DataInputStream( new BufferedInputStream(inputstream) ); Thread t = Thread.currentThread (); boolean eof = false; while(!eof){ try{ int i = in.readInt();
29、 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(); } } } //例
30、程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: 本站所有資源如無(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ì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 專題黨課講稿:以高質(zhì)量黨建保障國(guó)有企業(yè)高質(zhì)量發(fā)展
- 廉政黨課講稿材料:堅(jiān)決打好反腐敗斗爭(zhēng)攻堅(jiān)戰(zhàn)持久戰(zhàn)總體戰(zhàn)涵養(yǎng)風(fēng)清氣正的政治生態(tài)
- 在新錄用選調(diào)生公務(wù)員座談會(huì)上和基層單位調(diào)研座談會(huì)上的發(fā)言材料
- 總工會(huì)關(guān)于2025年維護(hù)勞動(dòng)領(lǐng)域政治安全的工作匯報(bào)材料
- 基層黨建工作交流研討會(huì)上的講話發(fā)言材料
- 糧食和物資儲(chǔ)備學(xué)習(xí)教育工作部署會(huì)上的講話發(fā)言材料
- 市工業(yè)園區(qū)、市直機(jī)關(guān)單位、市紀(jì)委監(jiān)委2025年工作計(jì)劃
- 檢察院政治部關(guān)于2025年工作計(jì)劃
- 辦公室主任2025年現(xiàn)實(shí)表現(xiàn)材料
- 2025年~村農(nóng)村保潔員規(guī)范管理工作方案
- 在深入貫徹中央8項(xiàng)規(guī)定精神學(xué)習(xí)教育工作部署會(huì)議上的講話發(fā)言材料4篇
- 開(kāi)展深入貫徹規(guī)定精神學(xué)習(xí)教育動(dòng)員部署會(huì)上的講話發(fā)言材料3篇
- 在司法黨組中心學(xué)習(xí)組學(xué)習(xí)會(huì)上的發(fā)言材料
- 國(guó)企黨委關(guān)于推動(dòng)基層黨建與生產(chǎn)經(jīng)營(yíng)深度融合工作情況的報(bào)告材料
- 副書(shū)記在2025年工作務(wù)虛會(huì)上的發(fā)言材料2篇
相關(guān)資源
更多