达拉草201771010105《面向对象程序设计(java)》第十六周学习总结
達拉草201771010105《面向對象程序設計(java)》第十六周學習總結
第一部分:理論知識
1.程序與進程的概念:
(1)程序是一段靜態的代碼,它是應用程序執行的藍 本。
(2)進程是程序的一次動態執行,它對應了從代碼加 載、執行至執行完畢的一個完整過程。
2.多線程的概念:
(1)多線程是進程執行過程中產生的多條執行線索。?
(2)多線程意味著一個程序的多行語句可以看上去幾 乎在同一時間內同時運行。?
(3)線程不能獨立存在,必須存在于進程中,同一進 程的各線程間共享進程空間的數據。?
Java實現多線程有兩種途徑:
創建Thread類的子類
在程序中定義實現Runnable接口的類
用Thread類的子類創建線程:
(1)首先需從Thread類派生出一個子類,在該子類中 重寫run()方法。?
例: class hand extends Thread {
public void run() {……}
}
(2)?然后用創建該子類的對象?
Lefthand left=new Lefthand();
Righthand right=new Righthand();?
(3)最后用start()方法啟動線程?
left.start();
right.start();
用Thread類的子類創建多線程的關鍵性操作:
(1)定義Thread類的子類并實現用戶線程操作,即 run()方法的實現。
(2)在適當的時候啟動線程。
由于Java只支持單重繼承,用這種方法定義的類不 可再繼承其他父類。
用Runnable()接口實現線程
(1)首先設計一個實現Runnable接口的類;?
(2)?然后在類中根據需要重寫run方法;?
(3)再創建該類對象,以此對象為參數建立Thread 類的對象;?
(4)調用Thread類對象的start方法啟動線程,將 CPU執行權轉交到run方法。
例如:
class A implements Runnable{
public void run(){….}
}
class B { public static void main(String[] arg){
Runnable a=new A();
Thread t=new Thread(a);
t.start();
}
}
線程的狀態:
(1)利用各線程的狀態變換,可以控制各個線程輪流 使用CPU,體現多線程的并行性特征。?
(2)線程有如下7種狀態:?
New (新建) 、Runnable (可運行) 、Running(運行) 、Blocked (被阻塞) 、Waiting (等待) 、Timed waiting (計時等待) 、Terminated (被終止)
新創建線程
new(新建) 線程對象剛剛創建,還沒有啟動,此時線程 還處于不可運行狀態。例如: Thread thread=new Thread(r);
可運行線程
(1)runnable(可運行狀態) ?此時線程已經啟動,處于線程的run()方法之 中。
(2)此時的線程可能運行,也可能不運行,只要 CPU一空閑,馬上就會運行。
(3)調用線程的start()方法可使線程處于“可運 行”狀態。例如: thread.start();
被阻塞線程和等待線程
?blocked (被阻塞):
阻塞時線程不能進入隊列排隊,必須等到引起 阻塞的原因消除,才可重新進入排隊隊列。?
sleep(),wait()是兩個常用引起線程阻塞的方法。
線程阻塞的三種情況:
(1)等待阻塞 :通過調用線程的wait()方法,讓線 程等待某工作的完成。?
(2)同步阻塞 :線程在獲取synchronized同步鎖失 敗(因為鎖被其它線程所占用),它會進入同步阻 塞狀態。?
(3)其他阻塞 :通過調用線程的sleep()或join() 或發出了I/O請求時,線程會進入到阻塞狀態。當 sleep()狀態超時、join()等待線程終止或者超 時、或者I/O處理完畢時,線程重新轉入就緒狀態。
被終止的線程
?Terminated (被終止) 線程被終止的原因有二:?
(1)一是run()方法中最后一個語句執行完畢而自 然死亡。?
(2)二是因為一個沒有捕獲的異常終止了run方法 而意外死亡。?
可以調用線程的stop 方 法 殺 死 一 個 線 程 (thread.stop();),但是,stop方法已過時, 不要在自己的代碼中調用它。
其他判斷和影響線程狀態的方法:
(1)join():等待指定線程的終止。?
(2)join(long millis):經過指定時間等待終止指定 的線程。?
(3)isAlive():測試當前線程是否在活動。?
(4)yield():讓當前線程由“運行狀態”進入到“就 緒狀態”,從而讓其它具有相同優先級的等待線程 獲取執行權。
多線程調度
(1)Java提供一個線程調度器來監控程序啟動后進入可運行狀態的所有線程。線程調度器按照線程的優先級決定應調度哪些線程來執行。
(2)處于可運行狀態的線程首先進入就緒隊列排隊等候處理器資源,同一時刻在就緒隊列中的線程可能有多個。Java的多線程系統會給每個線程自動分配一個線程的優先級。
?Java 的線程調度采用優先級策略:
(1)優先級高的先執行,優先級低的后執行;
(2)多線程系統會自動為每個線程分配一個優先級,缺省時,繼承其父類的優先級;
(3)任務緊急的線程,其優先級較高;
(4)同優先級的線程按“先進先出”的隊列原則;
守護線程
守護線程的惟一用途是為其他線程提供服務。例 如計時線程。
在一個線程啟動之前,調用setDaemon方法可 將線程轉換為守護線程(daemon thread)。 例如: setDaemon(true);
實驗十六 ?線程技術
實驗時間 2017-12-8
1、實驗目的與要求
(1) 掌握線程概念;
(2) 掌握線程創建的兩種技術;
(3) 理解和掌握線程的優先級屬性及調度方法;
(4) 掌握線程同步的概念及實現技術;
2、實驗內容和步驟
實驗1:測試程序并進行代碼注釋。
測試程序1:
l? 在elipse IDE中調試運行ThreadTest,結合程序運行結果理解程序;
l? 掌握線程概念;
l? 掌握用Thread的擴展類實現線程的方法;
l? 利用Runnable接口改造程序,掌握用Runnable接口創建線程的方法。
| class Lefthand extends Thread { ?? public void run() ?? { ?????? for(int i=0;i<=5;i++) ?????? { ?System.out.println("You are Students!"); ?????????? try{?? sleep(500);?? } ?????????? catch(InterruptedException e) ?????????? { System.out.println("Lefthand error.");}??? ?????? } ? } } class Righthand extends Thread { ??? public void run() ??? { ???????? for(int i=0;i<=5;i++) ???????? {?? System.out.println("I am a Teacher!"); ???????????? try{? sleep(300); ?} ???????????? catch(InterruptedException e) ????? ???????{ System.out.println("Righthand error.");} ???????? } ??? } } public class ThreadTest { ???? static Lefthand left; ???? static Righthand right; ???? public static void main(String[] args) ???? {???? left=new Lefthand(); ?????????? right=new Righthand(); ?????????? left.start(); ?????????? right.start(); ???? } } |
?
?程序運行結果如下:
利用Runnable接口改造程序:
1 package Demo; 2 3 class Lefthand implements Runnable { 4 public void run() 5 { 6 for(int i=0;i<=5;i++) 7 { System.out.println("You are Students!"); 8 try{ Thread.sleep(500);} 9 catch(InterruptedException e) 10 { System.out.println("Lefthand error.");} 11 } 12 } 13 } 14 class Righthand implements Runnable { 15 public void run() 16 { 17 for(int i=0;i<=5;i++) 18 { System.out.println("I am a Teacher!"); 19 try{ Thread.sleep(300); } 20 catch(InterruptedException e) 21 { System.out.println("Righthand error.");} 22 } 23 } 24 } 25 public class ThreadTest 26 { 27 static Lefthand left; 28 static Righthand right; 29 public static void main(String[] args) 30 { 31 Runnable left1=new Lefthand(); 32 Runnable right1=new Righthand(); 33 Thread left=new Thread(left1); 34 Thread right=new Thread(right1); 35 left.start(); 36 right.start(); 37 } 38 }運行結果如下:
測試程序2:
l? 在Elipse環境下調試教材625頁程序14-1、14-2 、14-3,結合程序運行結果理解程序;
l? 在Elipse環境下調試教材631頁程序14-4,結合程序運行結果理解程序;
l? 對比兩個程序,理解線程的概念和用途;
l? 掌握線程創建的兩種技術。
?
1 package bounce; 2 3 import java.awt.geom.*; 4 5 /** 6 * A ball that moves and bounces off the edges of a rectangle 7 * @version 1.33 2007-05-17 8 * @author Cay Horstmann 9 */ 10 public class Ball 11 { 12 private static final int XSIZE = 15; 13 private static final int YSIZE = 15; 14 private double x = 0; 15 private double y = 0; 16 private double dx = 1; 17 private double dy = 1; 18 19 /** 20 * Moves the ball to the next position, reversing direction if it hits one of the edges 21 */ 22 public void move(Rectangle2D bounds) 23 { 24 x += dx; 25 y += dy; 26 if (x < bounds.getMinX()) 27 { 28 x = bounds.getMinX(); 29 dx = -dx; 30 } 31 if (x + XSIZE >= bounds.getMaxX()) 32 { 33 x = bounds.getMaxX() - XSIZE; 34 dx = -dx; 35 } 36 if (y < bounds.getMinY()) 37 { 38 y = bounds.getMinY(); 39 dy = -dy; 40 } 41 if (y + YSIZE >= bounds.getMaxY()) 42 { 43 y = bounds.getMaxY() - YSIZE; 44 dy = -dy; 45 } 46 } 47 48 /** 49 * Gets the shape of the ball at its current position. 50 */ 51 public Ellipse2D getShape() 52 { 53 return new Ellipse2D.Double(x, y, XSIZE, YSIZE);//根據指定坐標構造和初始化 Ellipse2D。 54 } 55 } 1 package bounce; 2 3 import java.awt.*; 4 import java.util.*; 5 import javax.swing.*; 6 7 /** 8 * The component that draws the balls. 9 * @version 1.34 2012-01-26 10 * @author Cay Horstmann 11 */ 12 public class BallComponent extends JPanel 13 { 14 private static final int DEFAULT_WIDTH = 450; 15 private static final int DEFAULT_HEIGHT = 350; 16 17 private java.util.List<Ball> balls = new ArrayList<>(); 18 19 /** 20 * Add a ball to the component. 21 * @param b the ball to add 22 */ 23 public void add(Ball b) 24 { 25 balls.add(b); 26 } 27 28 public void paintComponent(Graphics g) 29 { 30 super.paintComponent(g); // erase background 31 Graphics2D g2 = (Graphics2D) g; 32 for (Ball b : balls) 33 { 34 g2.fill(b.getShape()); 35 } 36 } 37 38 public Dimension getPreferredSize() { return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT); } 39 } 1 package bounce; 2 3 import java.awt.*; 4 import java.awt.event.*; 5 import javax.swing.*; 6 7 /** 8 * Shows an animated bouncing ball. 9 * @version 1.34 2015-06-21 10 * @author Cay Horstmann 11 */ 12 public class Bounce 13 { 14 public static void main(String[] args) 15 { 16 EventQueue.invokeLater(() -> { 17 JFrame frame = new BounceFrame(); 18 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 19 frame.setVisible(true); 20 }); 21 } 22 } 23 24 /** 25 * The frame with ball component and buttons. 26 */ 27 class BounceFrame extends JFrame 28 { 29 private BallComponent comp; 30 public static final int STEPS = 1000; 31 public static final int DELAY = 3; 32 33 /** 34 * Constructs the frame with the component for showing the bouncing ball and 35 * Start and Close buttons 36 */ 37 public BounceFrame() 38 { 39 setTitle("Bounce"); 40 comp = new BallComponent(); 41 add(comp, BorderLayout.CENTER); 42 JPanel buttonPanel = new JPanel(); 43 addButton(buttonPanel, "Start", event -> addBall()); 44 addButton(buttonPanel, "Close", event -> System.exit(0)); 45 add(buttonPanel, BorderLayout.SOUTH); 46 pack(); 47 } 48 49 /** 50 * Adds a button to a container. 51 * @param c the container 52 * @param title the button title 53 * @param listener the action listener for the button 54 */ 55 public void addButton(Container c, String title, ActionListener listener) 56 { 57 JButton button = new JButton(title); 58 c.add(button); 59 button.addActionListener(listener); 60 } 61 62 /** 63 * Adds a bouncing ball to the panel and makes it bounce 1,000 times. 64 */ 65 public void addBall() 66 { 67 try 68 { 69 Ball ball = new Ball(); 70 comp.add(ball); 71 72 for (int i = 1; i <= STEPS; i++) 73 { 74 ball.move(comp.getBounds()); 75 comp.paint(comp.getGraphics()); 76 Thread.sleep(DELAY); 77 } 78 } 79 catch (InterruptedException e) 80 { 81 } 82 } 83 }運行結果如下:
在Elipse環境下調試教材631頁程序14-4,結合程序運行結果理解程序;
1 package bounceThread; 2 3 import java.awt.*; 4 import java.awt.event.*; 5 6 import javax.swing.*; 7 8 /** 9 * Shows animated bouncing balls. 10 * @version 1.34 2015-06-21 11 * @author Cay Horstmann 12 */ 13 public class BounceThread 14 { 15 public static void main(String[] args) 16 { 17 EventQueue.invokeLater(() -> { 18 JFrame frame = new BounceFrame(); 19 frame.setTitle("BounceThread"); 20 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 21 frame.setVisible(true); 22 }); 23 } 24 } 25 26 /** 27 * The frame with panel and buttons. 28 */ 29 class BounceFrame extends JFrame 30 { 31 private BallComponent comp; 32 public static final int STEPS = 1000; 33 public static final int DELAY = 5; 34 35 36 /** 37 * Constructs the frame with the component for showing the bouncing ball and 38 * Start and Close buttons 39 */ 40 public BounceFrame() 41 { 42 comp = new BallComponent(); 43 add(comp, BorderLayout.CENTER); 44 JPanel buttonPanel = new JPanel(); 45 addButton(buttonPanel, "Start", event -> addBall()); 46 addButton(buttonPanel, "Close", event -> System.exit(0)); 47 add(buttonPanel, BorderLayout.SOUTH); 48 pack(); 49 } 50 51 /** 52 * Adds a button to a container. 53 * @param c the container 54 * @param title the button title 55 * @param listener the action listener for the button 56 */ 57 public void addButton(Container c, String title, ActionListener listener) 58 { 59 JButton button = new JButton(title); 60 c.add(button); 61 button.addActionListener(listener); 62 } 63 64 /** 65 * Adds a bouncing ball to the canvas and starts a thread to make it bounce 66 */ 67 public void addBall() 68 { 69 Ball ball = new Ball(); 70 comp.add(ball); 71 Runnable r = () -> { 72 try 73 { 74 for (int i = 1; i <= STEPS; i++) 75 { 76 ball.move(comp.getBounds()); 77 comp.repaint(); 78 Thread.sleep(DELAY); 79 } 80 } 81 catch (InterruptedException e) 82 { 83 } 84 }; 85 Thread t = new Thread(r); 86 t.start(); 87 } 88 }運行結果如下;
測試程序3:分析以下程序運行結果并理解程序。
| class Race extends Thread { ? public static void main(String args[]) { ??? Race[] runner=new Race[4]; ?? ?for(int i=0;i<4;i++) runner[i]=new Race( ); ?? for(int i=0;i<4;i++) runner[i].start( ); ?? runner[1].setPriority(MIN_PRIORITY); ?? runner[3].setPriority(MAX_PRIORITY);} ? public void run( ) { ????? for(int i=0; i<1000000; i++); ????? System.out.println(getName()+"線程的優先級是"+getPriority()+"已計算完畢!"); ??? } } |
運行結果如下:
測試程序4
l? 教材642頁程序模擬一個有若干賬戶的銀行,隨機地生成在這些賬戶之間轉移錢款的交易。每一個賬戶有一個線程。在每一筆交易中,會從線程所服務的賬戶中隨機轉移一定數目的錢款到另一個隨機賬戶。
l? 在Elipse環境下調試教材642頁程序14-5、14-6,結合程序運行結果理解程序;
1 package synch; 2 3 import java.util.*; 4 import java.util.concurrent.locks.*; 5 6 /** 7 * A bank with a number of bank accounts that uses locks for serializing access. 8 * @version 1.30 2004-08-01 9 * @author Cay Horstmann 10 */ 11 public class Bank 12 { 13 private final double[] accounts; 14 private Lock bankLock; 15 private Condition sufficientFunds; 16 17 /** 18 * Constructs the bank. 19 * @param n the number of accounts 20 * @param initialBalance the initial balance for each account 21 */ 22 public Bank(int n, double initialBalance) 23 { 24 accounts = new double[n]; 25 Arrays.fill(accounts, initialBalance); 26 bankLock = new ReentrantLock(); 27 sufficientFunds = bankLock.newCondition(); 28 } 29 30 /** 31 * Transfers money from one account to another. 32 * @param from the account to transfer from 33 * @param to the account to transfer to 34 * @param amount the amount to transfer 35 */ 36 public void transfer(int from, int to, double amount) throws InterruptedException 37 { 38 bankLock.lock(); 39 try 40 { 41 while (accounts[from] < amount) 42 sufficientFunds.await(); 43 System.out.print(Thread.currentThread()); 44 accounts[from] -= amount; 45 System.out.printf(" %10.2f from %d to %d", amount, from, to); 46 accounts[to] += amount; 47 System.out.printf(" Total Balance: %10.2f%n", getTotalBalance()); 48 sufficientFunds.signalAll(); 49 } 50 finally 51 { 52 bankLock.unlock(); 53 } 54 } 55 56 /** 57 * Gets the sum of all account balances. 58 * @return the total balance 59 */ 60 public double getTotalBalance() 61 { 62 bankLock.lock(); 63 try 64 { 65 double sum = 0; 66 67 for (double a : accounts) 68 sum += a; 69 70 return sum; 71 } 72 finally 73 { 74 bankLock.unlock(); 75 } 76 } 77 78 /** 79 * Gets the number of accounts in the bank. 80 * @return the number of accounts 81 */ 82 public int size() 83 { 84 return accounts.length; 85 } 86 } 1 package synch; 2 3 /** 4 * This program shows how multiple threads can safely access a data structure. 5 * @version 1.31 2015-06-21 6 * @author Cay Horstmann 7 */ 8 public class SynchBankTest 9 { 10 public static final int NACCOUNTS = 100; 11 public static final double INITIAL_BALANCE = 1000; 12 public static final double MAX_AMOUNT = 1000; 13 public static final int DELAY = 10; 14 15 public static void main(String[] args) 16 { 17 Bank bank = new Bank(NACCOUNTS, INITIAL_BALANCE); 18 for (int i = 0; i < NACCOUNTS; i++) 19 { 20 int fromAccount = i; 21 Runnable r = () -> { 22 try 23 { 24 while (true) 25 { 26 int toAccount = (int) (bank.size() * Math.random()); 27 double amount = MAX_AMOUNT * Math.random(); 28 bank.transfer(fromAccount, toAccount, amount); 29 Thread.sleep((int) (DELAY * Math.random())); 30 } 31 } 32 catch (InterruptedException e) 33 { 34 } 35 }; 36 Thread t = new Thread(r); 37 t.start(); 38 } 39 } 40 }運行結果如下:
綜合編程練習
編程練習1
(1)? 用戶信息輸入界面如下圖所示:
?
(2)? 用戶點擊提交按鈕時,用戶輸入信息顯示控制臺界面;
(3)? 用戶點擊重置按鈕后,清空用戶已輸入信息;
(4)?? 點擊窗口關閉,程序退出。
package masn;import java.awt.EventQueue;import javax.swing.JFrame;public class Main {public static void main(String[] args) {EventQueue.invokeLater(() -> {DemoJFrame page = new DemoJFrame();});} } package masn;import java.awt.Dimension; import java.awt.Toolkit; import java.awt.Window;public class WinCenter {public static void center(Window win){Toolkit tkit = Toolkit.getDefaultToolkit();Dimension sSize = tkit.getScreenSize();Dimension wSize = win.getSize();if(wSize.height > sSize.height){wSize.height = sSize.height;}if(wSize.width > sSize.width){wSize.width = sSize.width;}win.setLocation((sSize.width - wSize.width)/ 2, (sSize.height - wSize.height)/ 2);} } package masn;import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.GridLayout;import javax.swing.BorderFactory; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JTextField;public class DemoJFrame extends JFrame {private JPanel jPanel1;private JPanel jPanel2;private JPanel jPanel3;private JPanel jPanel4;private JTextField fieldname;private JComboBox comboBox;private JTextField fieldadress;private ButtonGroup bg;private JRadioButton Male;private JRadioButton Female;private JCheckBox read;private JCheckBox sing;private JCheckBox dance;public DemoJFrame() {this.setSize(800, 400);this.setVisible(true);this.setTitle("Students Detail");this.setDefaultCloseOperation(EXIT_ON_CLOSE);WinCenter.center(this);jPanel1 = new JPanel();setJPanel1(jPanel1); jPanel2 = new JPanel();setJPanel2(jPanel2);jPanel3 = new JPanel();setJPanel3(jPanel3);jPanel4 = new JPanel();setJPanel4(jPanel4);FlowLayout flowLayout = new FlowLayout();this.setLayout(flowLayout);this.add(jPanel1);this.add(jPanel2);this.add(jPanel3);this.add(jPanel4);}/*設置面板一 */private void setJPanel1(JPanel jPanel) {jPanel.setPreferredSize(new Dimension(700, 45));jPanel.setLayout(new GridLayout(1, 4));JLabel name = new JLabel("name:");name.setSize(80, 30);fieldname = new JTextField("");fieldname.setSize(80, 20);JLabel study = new JLabel("qualification:");comboBox = new JComboBox();comboBox.addItem("初中");comboBox.addItem("高中");comboBox.addItem("本科");jPanel.add(name);jPanel.add(fieldname);jPanel.add(study);jPanel.add(comboBox);}/*設置面板二*/private void setJPanel2(JPanel jPanel) {jPanel.setPreferredSize(new Dimension(700, 50));jPanel.setLayout(new GridLayout(1, 4));JLabel name = new JLabel("address:");fieldadress = new JTextField();fieldadress.setPreferredSize(new Dimension(100, 50));JLabel study = new JLabel("hobby:");JPanel selectBox = new JPanel();selectBox.setBorder(BorderFactory.createTitledBorder(""));selectBox.setLayout(new GridLayout(3, 1));read = new JCheckBox("reading");sing = new JCheckBox("singing");dance = new JCheckBox("danceing");selectBox.add(read);selectBox.add(sing);selectBox.add(dance);jPanel.add(name);jPanel.add(fieldadress);jPanel.add(study);jPanel.add(selectBox);}/* 設置面板三 */private void setJPanel3(JPanel jPanel) {jPanel.setPreferredSize(new Dimension(700, 150));FlowLayout flowLayout = new FlowLayout(FlowLayout.LEFT);jPanel.setLayout(flowLayout);JLabel sex = new JLabel("性別:");JPanel selectBox = new JPanel();selectBox.setBorder(BorderFactory.createTitledBorder(""));selectBox.setLayout(new GridLayout(2, 1));bg = new ButtonGroup();Male = new JRadioButton("male");Female = new JRadioButton("female");bg.add(Male );bg.add(Female);selectBox.add(Male);selectBox.add(Female);jPanel.add(sex);jPanel.add(selectBox);}/*設置面板四*/private void setJPanel4(JPanel jPanel) {jPanel.setPreferredSize(new Dimension(700, 150));FlowLayout flowLayout = new FlowLayout(FlowLayout.CENTER, 50, 10);jPanel.setLayout(flowLayout);jPanel.setLayout(flowLayout);JButton sublite = new JButton("提交");JButton reset = new JButton("重置");sublite.addActionListener((e) -> valiData());reset.addActionListener((e) -> Reset());jPanel.add(sublite);jPanel.add(reset);}/*提交數據*/private void valiData() {String name = fieldname.getText().toString().trim();String xueli = comboBox.getSelectedItem().toString().trim();String address = fieldadress.getText().toString().trim();System.out.println(name);System.out.println(xueli);String hobbystring="";if (read.isSelected()) {hobbystring+="reading ";}if (sing.isSelected()) {hobbystring+="singing ";}if (dance.isSelected()) {hobbystring+="dancing ";}System.out.println(address);if (Male.isSelected()) {System.out.println("male");}if (Female.isSelected()) {System.out.println("female");}System.out.println(hobbystring);}/*重置*/private void Reset() {fieldadress.setText(null);fieldname.setText(null);comboBox.setSelectedIndex(0);read.setSelected(false);sing.setSelected(false);dance.setSelected(false);bg.clearSelection();} }運行結果如下:
? ??
2.創建兩個線程,每個線程按順序輸出5次“你好”,每個“你好”要標明來自哪個線程及其順序號。
1 package Demo; 2 3 class Lefthand extends Thread { 4 public void run() 5 { 6 for(int i=0;i<=5;i++) 7 { System.out.println("1.你好!"); 8 try{ sleep(500); } 9 catch(InterruptedException e) 10 { System.out.println("Lefthand error.");} 11 } 12 } 13 } 14 class Righthand extends Thread { 15 public void run() 16 { 17 for(int i=0;i<=5;i++) 18 { System.out.println("2.你好!"); 19 try{ sleep(300); } 20 catch(InterruptedException e) 21 { System.out.println("Righthand error.");} 22 } 23 } 24 } 25 public class ThreadTest 26 { 27 static Lefthand left; 28 static Righthand right; 29 public static void main(String[] args) 30 { left=new Lefthand(); 31 right=new Righthand(); 32 left.start(); 33 right.start(); 34 } 35 }運行結果如下:
3. 完善實驗十五 GUI綜合編程練習程序。
?實驗總結:
? ? ? ? ?這周我們學習了并發,然后學習了與線程有關的知識,學會了線程的創建方法。在這周的實驗中我們學習了用Thread類的子類創建線程,用Runnable()(見教材632頁)接口實現線程等。
轉載于:https://www.cnblogs.com/dalacao/p/10126003.html
總結
以上是生活随笔為你收集整理的达拉草201771010105《面向对象程序设计(java)》第十六周学习总结的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 小程序的项目结构设计
- 下一篇: Android输入系统(三)InputR