201871010119-帖佼佼《面向对象程序设计(java)》第十六周学习总结

时间:2019-12-18
本文章向大家介绍201871010119-帖佼佼《面向对象程序设计(java)》第十六周学习总结,主要包括201871010119-帖佼佼《面向对象程序设计(java)》第十六周学习总结使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

博文正文开头格式:(2分)

项目

内容

这个作业属于哪个课程

 https://www.cnblogs.com/nwnu-daizh/

这个作业的要求在哪里

   https://www.cnblogs.com/nwnu-daizh/p/11435127.html

作业学习目标

(1) 掌握菜单组件用途及常用API;

(2) 掌握对话框组件用途及常用API;

(3) 学习设计简单应用程序的GUI。

随笔博文正文内容包括:

第一部分:总结教材14.1-14.3知识内容(20分)

1、程序:一段静态的代码,应用程序执行的蓝本。

2、进程:是程序的一次动态执行,它对应了从代码加载、执行至执行完毕的一个完整过程。

  操作系统为每个进程分配一段独立的内存空间和系统资源,

  包括:代码数据以及堆栈等资源。每一个资源的内部数据和状态都是完全独立的。多任务操作系统中,进程切换对CPU资源消耗大。

3、多线程:进程执行过程中产生的多条执行线索,比进程执行更小的单位。

  线程是不能独立存在,必须存在于进程中,同一进程的各线程间共享进程空间的数据。

  每个线程有它自身的产生、存在和消亡的过程, 是一个动态的概念。

  多线程意味着一个程序的多行语句可以看上去几 乎在同一时间内同时运行。

  线程创建、销毁和切换的负荷远小于进程,又称 为轻量级进程。

4、Java实现多线程有两种途径:

  ——创建Thread类的子类

  ——在程序中定义实现Runnable接口的类

    class hand extends Thread

    {

     public  void run()

    {。。。。。}

    }

  用start()方法启动线程。

(1)用Thread类的子类创建多线程的关键性操作:

  ——定义Thread类的子类并实现用户线程操作,即 run()方法的实现。

  ——在适当的时候启动线程。

  由于Java只支持单重继承,用这种方法定义的类不 可再继承其他父类。

5、用Runnable()接口实现线程:

(1)首先设计一个实现Runnable接口的类;

(2)然后再类中根据需要重写run方法;

(3)再创建该类的对象,以此对象为参数建立Thread类的对象;

(4)调用Thread类对象的start方法启动线程,将CPU执行权交给run方法。

6、线程两种创建方法的比较:

实现Runnable接口的优势:

  (1)符合OO设计的思想;

  (2)便于用extends继承其他类;

采用继承Thread类的子类的方法优势:代码简单;

7、线程的终止:

(1)当线程的run方法执行方法体中最后一句语句后,或者出现了 在run方法体中没有捕获的异常时,线程将终止,让出CPU使用权;

(2)调用interput()方法也可以让线程终止;

void  interput()

(3)向一个线程发送一个中断请求,同时会把这个线程的“interput”状态置为true;

(4)若该线程处于blocked状态,会抛出interputedException。

8、测实线程是否被中断的方法:

Java提供了几个用于测实线程是否被中断的方法;

static   boolean   interputed()

检测当前线程是否被中断,并重置状态“interputed”值为false;

boolean   isinterputed()

检测当前线程是否已被中断,不改变状态“interputed”值。

9、线程的状态:

(1)利用各线程的状态的变换,可以控制各个线程轮流使用CPU,体现线程的并行性特征;

(2)线程有七种状态:

1)  New (新建)

2)  Runnable (可运行)

3)  Running (运行)

4)  Blocked (被阻塞)

5)  Waiting (等待)

6)  Timed waiting (计时等待)

7)  Timeinated (被终止)

线程状态:

1)  新建线程:

new(新建)

  线程对象刚刚创建,还没有启动,此时线程还处于不可运行状态。例如:

  Thread thread = new Thread(r);

  此时线程thread处于新建状态,又了相应内存空间以及其他资源。

2)可运行状态:

  runnable(可运行状态)

  此时线程已经启动,处于线程的run()方法之中;

  此时的线程可能马上运行,也可能不运行,只要CPU一空闲,马上就会运行;

  调用线程的start()方法可是=使线程处于“可运行状态”。例如:thread.start();

3) 被阻塞线程和等待线程

  blocked(被阻塞)

  一个正在执行的线程因特殊原因,被暂停执行,进入阻塞状态;

  阻塞时线程不能进入队列排队,必须等到引起阻塞的原因消除,才可以重新进入队列排队;

  引起阻塞的原因很多,不同原因要用不同的地方消除。

  sleep(),wait()是两个常用的引起线程阻塞的方法。

10、线程阻塞的三种情况:

(1)等待阻塞:通过调用线程的wait()方法,让线程等待某工作的完成;

(2)同步线程:线程在获取synchronized同步锁失败(因为锁被其他线程所占用),它会进入同步阻塞的状态;;

(3)其他阻塞:通过调用线程的sleep()或join()或发出了I/O请求时,线程会进入阻塞状态。当sleep()状态超时、join()等待线程终止或者超时、或者I/O处理完毕时,线程重新转入就绪状态。

11、被终止的线程:

 Timeinated (被终止)

  线程被终止的原因:

(1)run()方法中最后一个语句执行完毕而自然死亡;

(2)因为一个没有捕获的异常终止了run()方法而意外死亡;

可以调用线程的stop()方法杀死一个线程(thread.stop()),但是,stop()方法已经过时,不要再自己的代码中调用它。

12、线程的挂起和恢复:

  suspend()和   resume()方法:

  两个方法可配套使用。suspend()使得线程进入阻塞状态,并且不会自动恢复,必须器其对应的resume()被调用,才能使得线程重新进入可执行状态;

  这种方法容易引起死锁得问题。

13、其他判断和影响线程的方法:

  join():等待指定线程的终止;

  join(long   mills):经过指定时间等待终止指定的线程。

  isAlive():测试当前线程是否在活动;

  yield():让当前线程由“运行状态”进入到“就绪状态”进入到“就绪状态”,从而让它具有相同优先级的等待线程获取执行权。

14、多线程调度:

Java提供了一个线程调度器来监控程序启动后进入可运行状态的所有线程。线程调度器按照线程的优先级决定应调度哪些线程来执行;

处于可运行状态的线程首先进入就绪队列排队等待CPU资源,同一时刻就绪队列中的线程可能有多个。Java的多线程系统会给每一个线程自动分配一个优先级。

Java的线程调度采用优先级策略:

  优先级高的先执行,优先级低的后执行;

  多线程系统会给每一个线程分配一个优先级,缺省时,继承其父类的优先级;

  任务紧急的线程,其优先级较高;

  同优先级的线程按“先进先出”的队列原则。

15、Thread类有三个与线程有关的静态量:

MAX_PRIORITY:最大优先级,值为10;

MIN_PRIORITY:最小优先级,值为1:

NORM_PRIORITY:默认优先级,值为5.

调用setPriority(int  a)重置当前线程的优先级,a取值可以是前述的三个静态量;

调用getPriority()获取当前的线程优先级。

16、当前线程放弃CPU的情况:

  线程调用了yield()或sleep()方法:

  抢先式系统下,有高优先级的线程参与调度;

  由于当前线程进行I/O访问、外存读写、等待用户的输入操作等导致线程的阻塞;或者是为等候一个条件变量,以及线程调用wait()方法;

17、守护线程:

  守护线程的唯一用途就是为其他线程提供服务;

  若JVM的运行任务只剩下守护线程时,JVM就退出了;

  在一个线程启动之前,调用setDaemon方法可将线程转换为守护线程(daemon  thread)。

18、多线程并发存在问题:

  Java通过多线程的并发运行提高系统资源利用率,改善系统性能。

  存在问题:假设有两个或两个以上的线程共享某个对象,每个线程都调用了改变该对象类状态的方法。

  多个线程的相对执行顺序不确定;

  线程执行顺序不确定性会产生执行结果的不确定性;

  在多线程对共享数据操作时常常会产生不确定性。

19、线程的同步:

  多线程并发运行不确定性问题解决方案:

  引入线程同步机制;

在Java中线程同步方法有两种:

(1)JavaSE5.0中引入ReentrantLock类;

20、有关锁对象和条件对象的关键要点:

  锁用来保护代码片段,保证任何时刻只能有一个线程被保护执行的代码;

  锁管理试图进入被保护的代码段的线程;

  锁可拥有一个或多个相关的条件对象;

  每个条件对象管理那些已经进入被保护得到代码段但还不能运行的线程;

21、在临界区中使用条件对象的await()、signal()、signalAll()方法实现线程之间的交互:

  一个线程在临界区时,可能根据问题的需要,必须使用锁对象的await()方法使本线程等待,暂时让出CPU的使用权,并允许其他线程使用这个同步方法;

  线程若退出临界区,应用signal()方法随机的选择一个线程解除其阻塞状态;

  线程若退出临界区,执行notifyAll()方法通知所有由于等待该临界区的线程结束等待。

(2)在共享内存中的类方法前加synchronized修饰符;

  synchronized关键字作用:

  某个类内方法用synchronized修饰符后,该方法被称为同步线程;

  只要某个线程正在访问同步方法,其他线程欲要访问同步方法就会被阻塞,直至线程从同步方法返回前唤醒被阻塞线程,其他线程方法可能进入同步方法;

第二部分:实验部分

实验1:测试程序1(10分)

在elipse IDE中调试运行教材585页程序13-1,结合程序运行结果理解程序;

掌握创建JAR文件的方法;

实验代码如下:

package resource;

import java.awt.*;
import java.io.*;
import java.net.*;
import java.util.*;
import javax.swing.*;

/**
 * @version 1.41 2015-06-12
 * @author Cay Horstmann
 */
public class ResourceTest {                          // 整体框架的设置
	public static void main(String[] args) {
		EventQueue.invokeLater(() -> {
			JFrame frame = new ResourceTestFrame(); 
			frame.setTitle("ResourceTest");
			frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
			frame.setVisible(true);
		});
	}
}

/**
 * A frame that loads image and text resources.
 */
class ResourceTestFrame extends JFrame // 创建一个继承JFrame的子类ResourceTestFrame
{
	private static final int DEFAULT_WIDTH = 300; // 私有属性的定义
	private static final int DEFAULT_HEIGHT = 300;

	public ResourceTestFrame() // ResourceTestFrame构造器
	{
		setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); // 设置整体框架的大小
		URL aboutURL = getClass().getResource("about.gif"); // 在ResourceTest.class所处的当前目录下查找,读取文本
		Image img = new ImageIcon(aboutURL).getImage();
		setIconImage(img); // 定义用户关闭这个框架时的响应动作为关闭框架

		JTextArea textArea = new JTextArea();
		InputStream stream = getClass().getResourceAsStream("about.txt");
		// 找到与类同一位置的资源,返回一个可以加载的URL或者输入流.
		try (Scanner in = new Scanner(stream, "UTF-8")) {      //try——catch子句捕获异常
			while (in.hasNext())
				textArea.append(in.nextLine() + "\n");         //此文本域后面继续追加内容,把获取的下一行内容添加在文本框中。 
		}
		add(textArea);    //把文本域添加到框架当中
	}
}

  运行结果如下:

l  将所生成的JAR文件移到另外一个不同的目录中,再运行该归档文件,以便确认程序是从JAR文件中,而不是从当前目录中读取的资源。

过程及运行结果如下:

实验1:测试程序2(10分)

l  在elipse IDE中调试运行ThreadTest,结合程序运行结果理解程序;

l  掌握线程概念;

l  掌握用Thread的扩展类实现线程的方法;

实验代码如下:

class Lefthand extends Thread {      //继承Thread的子类Lefthand
	public void run() {              //run()方法
		for (int i = 0; i <= 5; i++) { 
			System.out.println("You are Students!");
			try {
				sleep(500);            //睡眠500毫秒
			} catch (InterruptedException e) {
				System.out.println("Lefthand error.");
			}
		}
	}
}

class Righthand extends Thread {			//继承Thread的子类Righthand
	public void run() {						//run()方法
		for (int i = 0; i <= 5; i++) {
			System.out.println("I am a Teacher!");
			try {
				sleep(300);					//睡眠300毫秒
			} catch (InterruptedException e) {
				System.out.println("Righthand error.");
			}
		}
	}
}

public class ThreadTest {             
	static Lefthand left;         		//Lefthand和Righthand类的定义
	static Righthand right;

	public static void main(String[] args) {
		left = new Lefthand();   		//新建一个Lefthand类
		right = new Righthand(); 		//新建一个Righthand类
		left.start();            	    //left开始执行
		right.start();					//right开始执行
	}
}

  运行结果如下:

l  利用Runnable接口改造程序,掌握用Runnable接口创建线程的方法。

实验代码如下:

class Lefthand implements Runnable {                 //实现Runnable接口的类Lefthand
    public void run() {								 //run()方法
        for (int i = 0; i <= 5; i++) {
            System.out.println("You are Students!");
            try {
                Thread.sleep(500);                   //睡眠500毫秒
            } catch (InterruptedException e) {
                System.out.println("Lefthand error.");
            }
        }
    }
}

class Righthand implements Runnable {                  //实现Runnable接口的类Righthand
    public void run() {								   //run()方法
        for (int i = 0; i <= 5; i++) {
            System.out.println("I am a Teacher!");
            try {
                Thread.sleep(300);                     //睡眠300毫秒
            } catch (InterruptedException e) {
                System.out.println("Righthand error.");
            }
        }
    }
}

public class ThreadTest {
    public static void main(String[] args) {
        Runnable left = new Lefthand();           
        Thread a = new Thread(left);        //创建一个线程
        Runnable right = new Righthand();
        Thread b = new Thread(right);
        a.start();                          //a开始
        b.start();                          //b开始
    }
}

  运行结果如下:

实验1:测试程序3(10分)

l  在Elipse环境下调试教材625页程序14-1、14-2 、14-3,结合程序运行结果理解程序;

l  对比两个程序,理解线程的概念和用途;

l  掌握线程创建的两种技术。

实验代码如下:

package bounce;

import java.awt.geom.*;

/**
 * A ball that moves and bounces off the edges of a rectangle
 * @version 1.33 2007-05-17
 * @author Cay Horstmann
 */
public class Ball            
{
   private static final int XSIZE = 15;         //私有常量的定义
   private static final int YSIZE = 15;
   private double x = 0;
   private double y = 0;	
   private double dx = 1;					  //dx和dy相当于 运行的速度 XSIZE和YSIZE在if作为了边界限制的判断条件.
   private double dy = 1;		

   /**
    * Moves the ball to the next position, reversing direction if it hits one of the edges
    */
   public void move(Rectangle2D bounds)       //move()方法,设置球的运动方向
   {
      x += dx;                            
      y += dy;
      if (x < bounds.getMinX())     		  //如果x小于边框的最小值     
      {
         x = bounds.getMinX();				  //则x就是变框的最小值
         dx = -dx;                            //变成反方向
      }
      if (x + XSIZE >= bounds.getMaxX())
      {
         x = bounds.getMaxX() - XSIZE;
         dx = -dx;
      }
      if (y < bounds.getMinY())
      {
         y = bounds.getMinY();
         dy = -dy;
      }
      if (y + YSIZE >= bounds.getMaxY())
      {
         y = bounds.getMaxY() - YSIZE;
         dy = -dy;
      }
   }

   /**
    * Gets the shape of the ball at its current position.
    */
   public Ellipse2D getShape()            //getShape()方法 设置球的外形       
   {
      return new Ellipse2D.Double(x, y, XSIZE, YSIZE);   
   }
}

  

package bounce;

import java.awt.*;
import java.util.*;
import javax.swing.*;

/**
 * The component that draws the balls.
 * 
 * @version 1.34 2012-01-26
 * @author Cay Horstmann
 */
public class BallComponent extends JPanel                   // BallComponent继承JPanel
{
	private static final int DEFAULT_WIDTH = 450;               // 私有常量的定义
	private static final int DEFAULT_HEIGHT = 350;

	private java.util.List<Ball> balls = new ArrayList<>();     //泛型数组
	
	/**
	 * Add a ball to the component.
	 * 
	 * @param b the ball to add
	 */
	public void add(Ball b) {                 			 //add方法,添加球
		balls.add(b);
	}

	public void paintComponent(Graphics g) {             //paintComponent方法
		super.paintComponent(g);// erase background
		Graphics2D g2 = (Graphics2D) g;
		for (Ball b : balls) {    
			g2.fill(b.getShape());                       //得到球的外形,将其填充
		}
	}

	public Dimension getPreferredSize() {              //获取组件的首选大小. 
		//Dimension类用来封装单个对象中组件的宽度和高度,所以用Dimension类封装起来以方便管理和使用这两个属性。
		return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT);
	}
}

  

package bounce;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/**
 * Shows an animated bouncing ball.
 * 
 * @version 1.34 2015-06-21
 * @author Cay Horstmann
 */
public class Bounce {
	public static void main(String[] args) 			// 设置整体框架
	{
		EventQueue.invokeLater(() -> {
			JFrame frame = new BounceFrame();
			frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
			frame.setVisible(true);
		});
	}
}

/**
 * The frame with ball component and buttons.
 */
class BounceFrame extends JFrame 				 // BounceFrame类继承JFrame
{
	private BallComponent comp; 				 // 私有的BallComponent类
	public static final int STEPS = 1000; 		 // 私有常量的定义,执行1000次
	public static final int DELAY = 3; 			 // 私有常量的定义,每次执行完延迟3毫秒

	/**
	 * Constructs the frame with the component for showing the bouncing ball and
	 * Start and Close buttons
	 */
	public BounceFrame() 						  // BounceFrame构造器
	{	
		setTitle("Bounce"); 					  //设置框架的名字为Bounce
		comp = new BallComponent(); 			  // 新建一个BallComponent类
		add(comp, BorderLayout.CENTER); 		  // 将新建的BallComponent类对象添加到框架当中,设置在边框布局管理器的CENTER位置
		JPanel buttonPanel = new JPanel();  	  //新建一个JPanel对象,buttonPanel面板
		addButton(buttonPanel, "Start", event -> addBall());
		//添加Start按钮到按钮面板当中,当Start执行时,将球添加到框架当中
		addButton(buttonPanel, "Close", event -> System.exit(0));
		//添加Close按钮到按钮面板当中
		add(buttonPanel, BorderLayout.SOUTH);      //添加按钮面板到框架当中,设置在边框布局管理器的SOUTH位置
		pack();                                    //调整组件的大小,考虑首选组件的大小
	}

	/**
	 * Adds a button to a container.
	 * 
	 * @param c        the container
	 * @param title    the button title
	 * @param listener the action listener for the button
	 */
	public void addButton(Container c, String title, ActionListener listener) {
		//addButton方法,三个入口参数
		JButton button = new JButton(title);        //新建一个按钮
		c.add(button);                              //添加按钮在容器c当中
		button.addActionListener(listener);         //添加按钮动作监听器
	}

	/**
	 * Adds a bouncing ball to the panel and makes it bounce 1,000 times.
	 */
	public void addBall() {                          //addBall方法
		try { 
			Ball ball = new Ball();
			comp.add(ball);
			
			for (int i = 1; i <= STEPS; i++) {        //当执行的次数小于1000时,球就会看起来像是在移动
				ball.move(comp.getBounds());		
				comp.paint(comp.getGraphics());       //重新绘制
				Thread.sleep(DELAY);				  //睡眠3毫秒
			}
		} catch (InterruptedException e) {            //线程中断异常处理
		}
	}
}

  运行结果如下:

l  在Elipse环境下调试教材631页程序14-4,结合程序运行结果理解程序;

实验代码如下:

  

package bounceThread;

import java.awt.geom.*;

/**
 * A ball that moves and bounces off the edges of a rectangle
 * @version 1.33 2007-05-17
 * @author Cay Horstmann
 */
public class Ball            
{
   private static final int XSIZE = 15;         //私有常量的定义
   private static final int YSIZE = 15;
   private double x = 0;
   private double y = 0;	
   private double dx = 1;					  //dx和dy相当于 运行的速度 XSIZE和YSIZE在if作为了边界限制的判断条件.
   private double dy = 1;		

   /**
    * Moves the ball to the next position, reversing direction if it hits one of the edges
    */
   public void move(Rectangle2D bounds)       //move()方法,设置球的运动方向
   {
      x += dx;                            
      y += dy;
      if (x < bounds.getMinX())     		  //如果x小于边框的最小值     
      {
         x = bounds.getMinX();				  //则x就是变框的最小值
         dx = -dx;                            //变成反方向
      }
      if (x + XSIZE >= bounds.getMaxX())
      {
         x = bounds.getMaxX() - XSIZE;
         dx = -dx;
      }
      if (y < bounds.getMinY())
      {
         y = bounds.getMinY();
         dy = -dy;
      }
      if (y + YSIZE >= bounds.getMaxY())
      {
         y = bounds.getMaxY() - YSIZE;
         dy = -dy;
      }
   }

   /**
    * Gets the shape of the ball at its current position.
    */
   public Ellipse2D getShape()            //getShape()方法 设置球的外形       
   {
      return new Ellipse2D.Double(x, y, XSIZE, YSIZE);   
   }
}

  

package bounceThread;

import java.awt.*;
import java.util.*;
import javax.swing.*;

/**
 * The component that draws the balls.
 * 
 * @version 1.34 2012-01-26
 * @author Cay Horstmann
 */
public class BallComponent extends JPanel                   // BallComponent继承JPanel
{
	private static final int DEFAULT_WIDTH = 450;               // 私有常量的定义
	private static final int DEFAULT_HEIGHT = 350;

	private java.util.List<Ball> balls = new ArrayList<>();     //泛型数组
	
	/**
	 * Add a ball to the component.
	 * 
	 * @param b the ball to add
	 */
	public void add(Ball b) {                 			 //add方法,添加球
		balls.add(b);
	}

	public void paintComponent(Graphics g) {             //paintComponent方法
		super.paintComponent(g);// erase background
		Graphics2D g2 = (Graphics2D) g;
		for (Ball b : balls) {    
			g2.fill(b.getShape());                       //得到球的外形,将其填充
		}
	}

	public Dimension getPreferredSize() {              //获取组件的首选大小. 
		//Dimension类用来封装单个对象中组件的宽度和高度,所以用Dimension类封装起来以方便管理和使用这两个属性。
		return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT);
	}
}

  

package bounceThread;

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

/**
 * Shows animated bouncing balls.
 * 
 * @version 1.34 2015-06-21
 * @author Cay Horstmann
 */
public class BounceThread // 整体框架的设置
{
	public static void main(String[] args) {
		EventQueue.invokeLater(() -> {
			JFrame frame = new BounceFrame();
			frame.setTitle("BounceThread");
			frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
			frame.setVisible(true);
		});
	}
}

/**
 * The frame with panel and buttons.
 */
class BounceFrame extends JFrame // BounceFrame继承JFrame
{
	private BallComponent comp; // 私有属性的定义
	public static final int STEPS = 1000; // 常量的定义
	public static final int DELAY = 5; // 私有常量的定义,每次执行完延迟3毫秒

	/**
	 * Constructs the frame with the component for showing the bouncing ball and
	 * Start and Close buttons
	 */
	public BounceFrame() // BounceFrame构造器
	{
		comp = new BallComponent(); // 新建一个BallComponent类对象
		add(comp, BorderLayout.CENTER); // 添加comp到边框布局管理器的CENTER的位置
		JPanel buttonPanel = new JPanel(); // 新建一个JPanel对象,buttonPanel面板
		addButton(buttonPanel, "Start", event -> addBall());
		// 添加Start按钮到按钮面板当中,当Start执行时,将球添加到框架当中
		addButton(buttonPanel, "Close", event -> System.exit(0));
		// 添加Close按钮到按钮面板当中
		add(buttonPanel, BorderLayout.SOUTH);
		// 添加按钮面板到框架当中,设置在边框布局管理器的SOUTH位置
		pack();// 调整组件的大小,考虑首选组件的大小
	}

	/**
	 * Adds a button to a container.
	 * 
	 * @param c        the container
	 * @param title    the button title
	 * @param listener the action listener for the button
	 */
	public void addButton(Container c, String title, ActionListener listener)
	// addButton方法,三个入口参数
	{
		JButton button = new JButton(title); // 新建一个按钮
		c.add(button); // 添加按钮在容器c当中
		button.addActionListener(listener); // 添加按钮动作监听器
	}

	/**
	 * Adds a bouncing ball to the canvas and starts a thread to make it bounce
	 */ 
	public void addBall() {              //addBall方法添加球
		Ball ball = new Ball();
		comp.add(ball);
		Runnable r = () -> {            //Runnable方法实现线程
			try { 
				for (int i = 1; i <= STEPS; i++) {
					ball.move(comp.getBounds());
					comp.repaint();        //重新绘制组件
					Thread.sleep(DELAY);   //线程延迟3毫秒
				}
			} catch (InterruptedException e) { //线程中断异常处理
			}
		};
		Thread t = new Thread(r);          //创建一个线程
		t.start();                         //调用start()方法开始执行
	}
}

  运行结果如下:

实验2:结对编程练习包含以下4部分:

采用GUI界面设计以下程序,并创建程序归档文件。

l  设计一个100以内整数小学生四则运算练习程序,由计算机随机产生10道加减乘除练习题,学生输入答案,由程序检查答案是否正确,每道题正确计10分,错误不计分,10道题测试结束后给出测试总分;

l  将程序中测试练习题及学生答题结果输出到文件,文件名为test.txt。

(该项17周实验课现场检查评分:30分)

1)   程序设计思路简述;

2)   符合编程规范的程序代码;

3)   程序运行功能界面截图;

实验总结:(15分)

    在本周学习了线程的知识,线程的两种创建,通过Thread类的子类来创建线程,更多推荐使用实现Runnable接口的方法,比较了两种方法的优势。理论知识比较少,代码理解的也还可以。关于线程,这一周就了解了它的创建。还有线程的终止等需要掌握。编程练习对我来说很有挑战性,但还是会自己试着做一下的。

原文地址:https://www.cnblogs.com/-8tjj/p/12040214.html