达拉草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页)接口实现线程等。

猜你喜欢

转载自www.cnblogs.com/dalacao/p/10126003.html
今日推荐