⚫ 線程的概念
⚫ 中斷線程
⚫ 線程狀態
⚫ 多線程調度
⚫ 線程同步java
1.程序與進程的概念編程
1.1程序是一段靜態的代碼,它是應用程序執行的藍 本。 數據結構
1.2進程是程序的一次動態執行,它對應了從代碼加載、執行至執行完畢的一個完整過程。 多線程
1.3操做系統爲每一個進程分配一段獨立的內存空間和系統資源,包括:代碼數據以及堆棧等資源。每個進程的內部數據和狀態都是徹底獨立的。 併發
1.4多任務操做系統中,進程切換對CPU資源消耗較大。框架
2.多線程的概念dom
2.1多線程是進程執行過程當中產生的多條執行線索。 ide
2.2線程是比進程執行更小的單位。 學習
2.3線程不能獨立存在,必須存在於進程中,同一進 程的各線程間共享進程空間的數據。 測試
2.4每一個線程有它自身的產生、存在和消亡的過程, 是一個動態的概念。
2.5多線程意味着一個程序的多行語句能夠看上去幾 乎在同一時間內同時運行。
2.6線程建立、銷燬和切換的負荷遠小於進程,又稱爲輕量級進程(lightweight process)。
2.7Java實現多線程有兩種途徑:
2.7.1建立Thread類的子類
2.7.2在程序中定義實現Runnable接口的類
3.線程的終止
3.1 當線程的run方法執行方法體中最後一條語句後, 或者出現了在run方法中沒有捕獲的異常時,線 程將終止,讓出CPU使用權。
3.2調用interrupt()方法也可終止線程。 void interrupt() –
3.2.1向一個線程發送一箇中斷請求,同時把這個線 程的「interrupted」狀態置爲true。
3.2.2若該線程處於blocked 狀態, 會拋出 InterruptedException。
4.測試線程是否被中斷的方法
Java提供了幾個用於測試線程是否被中斷的方法。
⚫ static boolean interrupted() – 檢測當前線程是否已被中斷, 並重置狀態 「interrupted」值爲false。
⚫ boolean isInterrupted() – 檢測當前線程是否已被中斷, 不改變狀態 「interrupted」值 。
5.線程的狀態
⚫ 利用各線程的狀態變換,能夠控制各個線程輪流 使用CPU,體現多線程的並行性特徵。
⚫ 線程有以下7種狀態: ➢New (新建) ➢Runnable (可運行) ➢Running(運行) ➢Blocked (被阻塞) ➢Waiting (等待) ➢Timed waiting (計時等待) ➢Terminated (被終止)
6.守護線程
⚫ 守護線程的唯一用途是爲其餘線程提供服務。例 如計時線程。
⚫ 若JVM的運行任務只剩下守護線程時,JVM就退 出了。
⚫ 在一個線程啓動以前,調用setDaemon方法可 將線程轉換爲守護線程(daemon thread)。
例如: setDaemon(true);
實驗時間 2017-12-8
1、實驗目的與要求
(1) 掌握線程概念;
(2) 掌握線程建立的兩種技術;
(3) 理解和掌握線程的優先級屬性及調度方法;
(4) 掌握線程同步的概念及實現技術;
2、實驗內容和步驟
實驗1:測試程序並進行代碼註釋。
測試程序1:
1.在elipse IDE中調試運行ThreadTest,結合程序運行結果理解程序;
2.掌握線程概念;
3.掌握用Thread的擴展類實現線程的方法;
4.利用Runnable接口改造程序,掌握用Runnable接口建立線程的方法。
1 class Lefthand extends Thread { 2 public void run() 3 { 4 for(int i=0;i<=5;i++) 5 { System.out.println("You are Students!"); 6 try{ sleep(500); } 7 catch(InterruptedException e) 8 { System.out.println("Lefthand error.");} 9 } 10 } 11 } 12 class Righthand extends Thread { 13 public void run() 14 { 15 for(int i=0;i<=5;i++) 16 { System.out.println("I am a Teacher!"); 17 try{ sleep(300); } 18 catch(InterruptedException e) 19 { System.out.println("Righthand error.");} 20 } 21 } 22 } 23 public class ThreadTest { 24 static Lefthand left; 25 static Righthand right; 26 27 28 public static void main(String[] args) 29 { left=new Lefthand(); 30 right=new Righthand(); 31 left.start(); 32 right.start(); 33 } 34 }
改:
1 class Lefthand implements Runnable { 2 public void run() 3 { 4 for(int i=0;i<=5;i++) 5 { System.out.println("You are Students!"); 6 try{ Thread.sleep(500); } 7 catch(InterruptedException e) 8 { System.out.println("Lefthand error.");} 9 } 10 } 11 } 12 class Righthand implements Runnable { 13 public void run() 14 { 15 for(int i=0;i<=5;i++) 16 { System.out.println("I am a Teacher!"); 17 try{ Thread.sleep(300); } 18 catch(InterruptedException e) 19 { System.out.println("Righthand error.");} 20 } 21 } 22 } 23 24 public class fufj { 25 26 static Thread left; 27 static Thread right; 28 29 public static void main(String[] args) 30 { 31 Runnable rleft = new Lefthand(); 32 Runnable rright = new Righthand(); 33 left = new Thread(rleft); 34 right = new Thread(rright); 35 left.start(); 36 right.start(); 37 } 38 39 } 40
測試程序2:
1.在Elipse環境下調試教材625頁程序14-一、14-2 、14-3,結合程序運行結果理解程序;
2.在Elipse環境下調試教材631頁程序14-4,結合程序運行結果理解程序;
3.對比兩個程序,理解線程的概念和用途;
4.掌握線程建立的兩種技術。
1 package bounce; 2 3 import java.awt.geom.*; 4 5 /** 6 * 彈球從矩形的邊緣上移動和彈出的球 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 * 將球移動到下一個位置,若是球擊中一個邊緣,則向相反的方向移動。 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 * 獲取當前位置的球的形狀。 50 */ 51 public Ellipse2D getShape() 52 { 53 return new Ellipse2D.Double(x, y, XSIZE, YSIZE); 54 } 55 }
1 package bounce; 2 3 import java.awt.*; 4 import java.util.*; 5 import javax.swing.*; 6 7 /** 8 * 拉球的部件。 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 * 向組件中添加一個球。 21 * @param b要添加的球 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); // 擦除背景 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 * 顯示一個動畫彈跳球。 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 * 框架與球組件和按鈕。 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 * 用顯示彈跳球的組件構造框架,以及開始和關閉按鈕 35 */ 36 public BounceFrame() 37 { 38 setTitle("Bounce"); 39 comp = new BallComponent(); 40 add(comp, BorderLayout.CENTER); 41 JPanel buttonPanel = new JPanel(); 42 addButton(buttonPanel, "Start", event -> addBall()); 43 addButton(buttonPanel, "Close", event -> System.exit(0)); 44 add(buttonPanel, BorderLayout.SOUTH); 45 pack(); 46 } 47 48 /** 49 * 向容器添加按鈕。 50 * @param c容器 51 * @param title 按鈕標題 52 * @param 監聽按鈕的操做監聽器 53 */ 54 public void addButton(Container c, String title, ActionListener listener) 55 { 56 JButton button = new JButton(title); 57 c.add(button); 58 button.addActionListener(listener); 59 } 60 61 /** 62 * 在面板上添加一個彈跳球,使其彈跳1000次。 63 */ 64 public void addBall() 65 { 66 try 67 { 68 Ball ball = new Ball(); 69 comp.add(ball); 70 71 for (int i = 1; i <= STEPS; i++) 72 { 73 ball.move(comp.getBounds()); 74 comp.paint(comp.getGraphics()); 75 Thread.sleep(DELAY); 76 } 77 } 78 catch (InterruptedException e) 79 { 80 } 81 } 82 }
1 package bounceThread; 2 3 import java.awt.geom.*; 4 5 /** 6 彈球從矩形的邊緣上移動和彈出的球 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 將球移動到下一個位置,若是球擊中一個邊緣,則向相反的方向移動。 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 獲取當前位置的球的形狀。 50 */ 51 public Ellipse2D getShape() 52 { 53 return new Ellipse2D.Double(x, y, XSIZE, YSIZE); 54 } 55 }
1 package bounceThread; 2 3 import java.awt.*; 4 import java.util.*; 5 import javax.swing.*; 6 7 /** 8 * 拉球的部件。 9 * @version 1.34 2012-01-26 10 * @author Cay Horstmann 11 */ 12 public class BallComponent extends JComponent 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 * 在面板上添加一個球。 21 * @param b要添加的球 22 */ 23 public void add(Ball b) 24 { 25 balls.add(b); 26 } 27 28 public void paintComponent(Graphics g) 29 { 30 Graphics2D g2 = (Graphics2D) g; 31 for (Ball b : balls) 32 { 33 g2.fill(b.getShape()); 34 } 35 } 36 37 public Dimension getPreferredSize() { return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT); } 38 }
1 package bounceThread; 2 3 import java.awt.*; 4 import java.awt.event.*; 5 6 import javax.swing.*; 7 8 /** 9 * 顯示動畫彈跳球。 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 * 帶有面板和按鈕的框架。 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 * 用顯示彈跳球以及開始和關閉按鈕的組件構建框架 38 */ 39 public BounceFrame() 40 { 41 comp = new BallComponent(); 42 add(comp, BorderLayout.CENTER); 43 JPanel buttonPanel = new JPanel(); 44 addButton(buttonPanel, "Start", event -> addBall()); 45 addButton(buttonPanel, "Close", event -> System.exit(0)); 46 add(buttonPanel, BorderLayout.SOUTH); 47 pack(); 48 } 49 50 /** 51 * 向容器添加按鈕。 52 * @param c 容器 53 * @param title 按鈕標題 54 * @param listener 按鈕的操做監聽器 55 */ 56 public void addButton(Container c, String title, ActionListener listener) 57 { 58 JButton button = new JButton(title); 59 c.add(button); 60 button.addActionListener(listener); 61 } 62 63 /** 64 * 在畫布上添加一個彈跳球,並啓動一個線程使其彈跳 65 */ 66 public void addBall() 67 { 68 Ball ball = new Ball(); 69 comp.add(ball); 70 Runnable r = () -> { 71 try 72 { 73 for (int i = 1; i <= STEPS; i++) 74 { 75 ball.move(comp.getBounds()); 76 comp.repaint(); 77 Thread.sleep(DELAY); 78 } 79 } 80 catch (InterruptedException e) 81 { 82 } 83 }; 84 Thread t = new Thread(r); 85 t.start(); 86 } 87 }
測試程序3:分析如下程序運行結果並理解程序。
1 class Race extends Thread { 2 public static void main(String args[]) { 3 Race[] runner=new Race[4]; 4 for(int i=0;i<4;i++) runner[i]=new Race( ); 5 for(int i=0;i<4;i++) runner[i].start( ); 6 runner[1].setPriority(MIN_PRIORITY); 7 runner[3].setPriority(MAX_PRIORITY);} 8 public void run( ) { 9 for(int i=0; i<1000000; i++); 10 System.out.println(getName()+"線程的優先級是"+getPriority()+"已計算完畢!"); 11 } 12 }
測試代碼
1 package vb; 2 3 public class asd { 4 static class Race extends Thread { 5 public static void main(String[] args) { 6 Race[] runner=new Race[4]; 7 for(int i=0;i<4;i++) runner[i]=new Race( ); 8 for(int i=0;i<4;i++) runner[i].start( ); 9 runner[1].setPriority(MIN_PRIORITY); 10 runner[3].setPriority(MAX_PRIORITY);} 11 public void run( ) { 12 for(int i=0; i<1000000; i++);//延時做用 13 System.out.println(getName()+"線程的優先級是"+getPriority()+"已計算完畢!"); 14 } 15 } 16 17 }
測試程序4
1.教材642頁程序模擬一個有若干帳戶的銀行,隨機地生成在這些帳戶之間轉移錢款的交易。每個帳戶有一個線程。在每一筆交易中,會從線程所服務的帳戶中隨機轉移必定數目的錢款到另外一個隨機帳戶。
2.在Elipse環境下調試教材642頁程序14-五、14-6,結合程序運行結果理解程序;
1 package unsynch; 2 3 import java.util.*; 4 5 /** 6 * 有許多銀行帳戶的銀行。 7 * @version 1.30 2004-08-01 8 * @author Cay Horstmann 9 */ 10 public class Bank 11 { 12 private final double[] accounts; 13 14 /** 15 * 建設銀行。 16 * @param n 帳號 17 * @param initialBalance 每一個帳戶的初始餘額 18 */ 19 public Bank(int n, double initialBalance) 20 { 21 accounts = new double[n]; 22 Arrays.fill(accounts, initialBalance); 23 } 24 25 /** 26 * 把錢從一個帳戶轉到另外一個帳戶。 27 * @param from 轉帳帳戶 28 * @param to 轉帳帳戶 29 * @param amount 轉帳金額 30 */ 31 public void transfer(int from, int to, double amount) 32 { 33 if (accounts[from] < amount) return; 34 System.out.print(Thread.currentThread()); 35 accounts[from] -= amount; 36 System.out.printf(" %10.2f from %d to %d", amount, from, to); 37 accounts[to] += amount; 38 System.out.printf(" Total Balance: %10.2f%n", getTotalBalance()); 39 } 40 41 /** 42 * 獲取全部賬戶餘額的總和。 43 * @return 總餘額 44 */ 45 public double getTotalBalance() 46 { 47 double sum = 0; 48 49 for (double a : accounts) 50 sum += a; 51 52 return sum; 53 } 54 55 /** 56 * 獲取銀行中的賬戶數量。 57 * @return 帳號 58 */ 59 public int size() 60 { 61 return accounts.length; 62 } 63 }
1 package unsynch; 2 3 /** 4 * 此程序顯示多個線程訪問數據結構時的數據損壞。 5 * @version 1.31 2015-06-21 6 * @author Cay Horstmann 7 */ 8 public class UnsynchBankTest 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.設計一個用戶信息採集程序,要求以下:
(1) 用戶信息輸入界面以下圖所示:
(2) 用戶點擊提交按鈕時,用戶輸入信息顯示控制檯界面;
(3) 用戶點擊重置按鈕後,清空用戶已輸入信息;
(4) 點擊窗口關閉,程序退出。
1 package 程序一; 2 3 import java.awt.EventQueue; 4 5 import javax.swing.JFrame; 6 7 public class First_exercise { 8 public static void main(String[] args) { 9 EventQueue.invokeLater(() -> { 10 DemoJFrame JFrame = new DemoJFrame(); 11 }); 12 } 13 }
1 package 程序一; 2 3 4 import java.awt.Color; 5 import java.awt.Dimension; 6 import java.awt.FlowLayout; 7 import java.awt.GridLayout; 8 import java.awt.LayoutManager; 9 import java.awt.Panel; 10 import java.awt.event.ActionEvent; 11 import java.awt.event.ActionListener; 12 13 import java.io.BufferedReader; 14 import java.io.File; 15 import java.io.FileInputStream; 16 import java.io.IOException; 17 import java.io.InputStreamReader; 18 19 import java.util.ArrayList; 20 import java.util.Timer; 21 import java.util.TimerTask; 22 23 import javax.swing.BorderFactory; 24 import javax.swing.ButtonGroup; 25 import javax.swing.ButtonModel; 26 import javax.swing.JButton; 27 import javax.swing.JCheckBox; 28 import javax.swing.JComboBox; 29 import javax.swing.JFrame; 30 import javax.swing.JLabel; 31 import javax.swing.JPanel; 32 import javax.swing.JRadioButton; 33 import javax.swing.JTextField; 34 35 public class DemoJFrame extends JFrame { 36 private JPanel jPanel1; 37 private JPanel jPanel2; 38 private JPanel jPanel3; 39 private JPanel jPanel4; 40 private JTextField fieldname; 41 private JComboBox comboBox; 42 private JTextField fieldadress; 43 private ButtonGroup Button; 44 private JRadioButton Male; 45 private JRadioButton Female; 46 private JCheckBox sing; 47 private JCheckBox dance; 48 private JCheckBox draw; 49 50 public DemoJFrame() { 51 this.setSize(750, 450); 52 this.setVisible(true); 53 this.setTitle("Student Detail"); 54 this.setDefaultCloseOperation(EXIT_ON_CLOSE); 55 Windows.center(this); 56 jPanel1 = new JPanel(); 57 setJPanel1(jPanel1); 58 jPanel2 = new JPanel(); 59 setJPanel2(jPanel2); 60 jPanel3 = new JPanel(); 61 setJPanel3(jPanel3); 62 jPanel4 = new JPanel(); 63 setJPanel4(jPanel4); 64 FlowLayout flowLayout = new FlowLayout(); 65 this.setLayout(flowLayout); 66 this.add(jPanel1); 67 this.add(jPanel2); 68 this.add(jPanel3); 69 this.add(jPanel4); 70 71 } 72 73 private void setJPanel1(JPanel jPanel) { 74 jPanel.setPreferredSize(new Dimension(700, 45)); 75 jPanel.setLayout(new GridLayout(1, 4)); 76 JLabel name = new JLabel("Name:"); 77 name.setSize(100, 50); 78 fieldname = new JTextField(""); 79 fieldname.setSize(80, 20); 80 JLabel study = new JLabel("Qualification:"); 81 comboBox = new JComboBox(); 82 comboBox.addItem("Graduate"); 83 comboBox.addItem("senior"); 84 comboBox.addItem("Undergraduate"); 85 jPanel.add(name); 86 jPanel.add(fieldname); 87 jPanel.add(study); 88 jPanel.add(comboBox); 89 90 } 91 92 private void setJPanel2(JPanel jPanel) { 93 jPanel.setPreferredSize(new Dimension(700, 50)); 94 jPanel.setLayout(new GridLayout(1, 4)); 95 JLabel name = new JLabel("Address:"); 96 fieldadress = new JTextField(); 97 fieldadress.setPreferredSize(new Dimension(150, 50)); 98 JLabel study = new JLabel("Hobby:"); 99 JPanel selectBox = new JPanel(); 100 selectBox.setBorder(BorderFactory.createTitledBorder("")); 101 selectBox.setLayout(new GridLayout(3, 1)); 102 sing = new JCheckBox("Singing"); 103 dance = new JCheckBox("Dancing"); 104 draw = new JCheckBox("Reading"); 105 selectBox.add(sing); 106 selectBox.add(dance); 107 selectBox.add(draw); 108 jPanel.add(name); 109 jPanel.add(fieldadress); 110 jPanel.add(study); 111 jPanel.add(selectBox); 112 } 113 114 private void setJPanel3(JPanel jPanel) { 115 jPanel.setPreferredSize(new Dimension(700, 150)); 116 FlowLayout flowLayout = new FlowLayout(FlowLayout.LEFT); 117 jPanel.setLayout(flowLayout); 118 JLabel sex = new JLabel("Sex:"); 119 JPanel selectBox = new JPanel(); 120 selectBox.setBorder(BorderFactory.createTitledBorder("")); 121 selectBox.setLayout(new GridLayout(2, 1)); 122 Button = new ButtonGroup(); 123 Male = new JRadioButton("Male"); 124 Female = new JRadioButton("Female"); 125 Button.add(Male); 126 Button.add(Female); 127 selectBox.add(Male); 128 selectBox.add(Female); 129 jPanel.add(sex); 130 jPanel.add(selectBox); 131 132 } 133 134 private void setJPanel4(JPanel jPanel) { 135 // TODO 自動生成的方法存根 136 jPanel.setPreferredSize(new Dimension(700, 150)); 137 FlowLayout flowLayout = new FlowLayout(FlowLayout.CENTER, 50, 10); 138 jPanel.setLayout(flowLayout); 139 jPanel.setLayout(flowLayout); 140 JButton sublite = new JButton("Validate"); 141 JButton reset = new JButton("Reset"); 142 sublite.addActionListener((e) -> valiData()); 143 reset.addActionListener((e) -> Reset()); 144 jPanel.add(sublite); 145 jPanel.add(reset); 146 } 147 148 private void valiData() { 149 String name = fieldname.getText().toString().trim(); 150 String xueli = comboBox.getSelectedItem().toString().trim(); 151 String address = fieldadress.getText().toString().trim(); 152 System.out.println(name); 153 System.out.println(xueli); 154 String hobbystring=""; 155 if (sing.isSelected()) { 156 hobbystring+="Singing "; 157 } 158 if (dance.isSelected()) { 159 hobbystring+="Dancing "; 160 } 161 if (draw.isSelected()) { 162 hobbystring+="Reading "; 163 } 164 System.out.println(address); 165 if (Male.isSelected()) { 166 System.out.println("Male"); 167 } 168 if (Female.isSelected()) { 169 System.out.println("Female"); 170 } 171 System.out.println(hobbystring); 172 } 173 174 private void Reset() { 175 fieldadress.setText(null); 176 fieldname.setText(null); 177 comboBox.setSelectedIndex(0); 178 sing.setSelected(false); 179 dance.setSelected(false); 180 draw.setSelected(false); 181 Button.clearSelection(); 182 } 183 }
1 package 程序一; 2 3 4 import java.awt.Dimension; 5 import java.awt.Toolkit; 6 import java.awt.Window; 7 8 public class Windows { 9 public static void center(Window win){ 10 Toolkit tkit = Toolkit.getDefaultToolkit(); 11 Dimension sSize = tkit.getScreenSize(); 12 Dimension wSize = win.getSize(); 13 14 if(wSize.height > sSize.height){ 15 wSize.height = sSize.height; 16 } 17 18 if(wSize.width > sSize.width){ 19 wSize.width = sSize.width; 20 } 21 22 win.setLocation((sSize.width - wSize.width)/ 2, (sSize.height - wSize.height)/ 2); 23 } 24 }
2.建立兩個線程,每一個線程按順序輸出5次「你好」,每一個「你好」要標明來自哪一個線程及其順序號。
1 package 程序二; 2 3 class Lefthand implements Runnable { 4 public void run(){ 5 for(int i=1;i<=5;i++) 6 { System.out.println(" Lefthand "+i+" 你好"); 7 try{ Thread.sleep(500); } 8 catch(InterruptedException e) 9 { System.out.println("Lefthand error.");} 10 } 11 } 12 } 13 class Righthand implements Runnable { 14 public void run(){ 15 for(int i=1;i<=5;i++) 16 { System.out.println(" Righthand "+i+" 你好"); 17 try{ Thread.sleep(300); } 18 catch(InterruptedException e) 19 { System.out.println("Righthand error.");} 20 } 21 } 22 } 23 24 public class Second_exercise { 25 26 static Thread left; 27 static Thread right; 28 29 public static void main(String[] args){ 30 Runnable rleft = new Lefthand(); 31 Runnable rright = new Righthand(); 32 left = new Thread(rleft); 33 right = new Thread(rright); 34 left.start(); 35 right.start(); 36 } 37 38 }
3. 完善實驗十五 GUI綜合編程練習程序。
經過本週的學習,我掌握了線程概念;線程建立的兩種技術;理解和掌握了基礎線程的優先級屬性及調度方法;學會了Java GUI 編程技術的基礎。由於要考四級因此學習時間有所減小,這部分學習不是很紮實,在之後的學習中會繼續鞏固學習。