1. 程式人生 > >王之泰 201771010131《面向物件程式設計(java)》第十六週學習總結

王之泰 201771010131《面向物件程式設計(java)》第十六週學習總結

 

 

第一部分:理論知識學習部分

第14章 併發

⚫ 執行緒的概念
⚫ 中斷執行緒
⚫ 執行緒狀態
⚫ 多執行緒排程
⚫ 執行緒同步

 

1.程式與程序的概念

1.1程式是一段靜態的程式碼,它是應用程式執行的藍 本。

1.2程序是程式的一次動態執行,它對應了從程式碼載入、執行至執行完畢的一個完整過程。

1.3作業系統為每個程序分配一段獨立的記憶體空間和系統資源,包括:程式碼資料以及堆疊等資源。每一個程序的內部資料和狀態都是完全獨立的。

1.4多工作業系統中,程序切換對CPU資源消耗較大。

2.多執行緒的概念

2.1多執行緒是程序執行過程中產生的多條執行線索。

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-1、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 }
Ball
 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 }
BallComponent
 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 }
Bounce

 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 }
Ball
 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 }
BallComponent
 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 }
BounceThread

測試程式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-5、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 }
Bank
 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 }
UnsynchBankTest

 

 

綜合程式設計練習

程式設計練習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 }
First_exercise
  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 }
DemoJFrame
 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 }
Windows

 

 

 

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 }
Second_exercise

 

3. 完善實驗十五 GUI綜合程式設計練習程式。

 

 第三部分:總結

     通過