1. 程式人生 > >達拉草201771010105《面向物件程式設計(java)》第十六週學習總結

達拉草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. 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頁)介面實現執行緒等。