201871010119- posts Jiaojiao "object-oriented programming (java)" Week 16 learning summary

Bowen beginning of the text format: (2 points)

project

content

This work belongs courses

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

Where this requirement in the job

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

Job learning objectives

(1) and common control menu component uses the API;

(2) Common control box assembly and use the API;

(3) learn to design simple application GUI.

Essay Bowen body content include:

Part I: summary of the intellectual content of textbooks 14.1-14.3 (20 points)

1, the program: a period of static code, modeled on the execution of the application.

2, process: a dynamic execution program, which corresponds to the load from the code, a complete process execution to execution completed.

  The operating system allocates space for a separate memory and system resources for each process,

  Comprising: a stack code data and other resources. Internal data and the status of each resource is completely independent. Multi-tasking operating system, the process of switching to CPU resource consumption.

3, Multithreading: multiple execution leads generated during process execution, execution smaller units than the process.

  A thread is not independent existence, it must exist in the process, among threads of the same process of data sharing process space.

  Each thread has its own production, existence and demise of the process, is a dynamic concept.

  Multi-line statement means that a multithreaded program can run simultaneously looked almost at the same time.

  Thread creation, destruction and load switching is much smaller than the process, also known as lightweight processes.

4, Java multi-threaded in two ways:

  - create a subclass of the Thread class

  - define the implementation Runnable interface class in the program

    class hand extends Thread

    {

     public  void run()

    {。。。。。}

    }

  With start () method to start a thread.

(1) create critical operations with multi-threaded Thread subclass:

  - Thread subclass definition class operation and implement user threads, i.e. to achieve run () method.

  - Start the thread at the appropriate time.

  Because Java only supports single inheritance, class defined in this way can no longer inherit other parent.

5, with Runnable () interface thread:

(1) First, the design of a class that implements Runnable interface;

(2) The class and then run method needs to be rewritten;

(3) re-create objects of that class, in order to establish the object of the Thread class objects as parameters;

start method (4) calls the Thread class object to start the thread, the CPU implementation of the right to run method.

6. Comparison of two methods to create a thread:

Runnable interface to achieve the advantages of:

  (1) comply with OO design ideas;

  (2) to facilitate use other classes inherit the extends;

Thread class using subclass inherits the advantages of the method: the code is simple;

7, the thread termination:

(1) When the run method of the thread execution method body in the last sentence of the statement, or there has been an exception in the run method body is not caught, the thread will terminate, allowing the CPU use right;

(2) call interput () method also allows the thread termination;

void  interput()

(3) a thread sends an interrupt request, and will "interput" state of the thread is set to true;

(4) If the thread is blocked state, it will throw interputedException.

8, whether real test thread is interrupted method:

Java provides several methods for measuring whether real thread has been interrupted;

static   boolean   interputed()

Detecting whether the current thread is interrupted, and reset the state "interputed" is false;

boolean   isinterputed()

Detecting whether the current thread has been interrupted, does not change the state "interputed" value.

9, the state of the thread:

Converting (1) state by each thread, each thread turn can be controlled using the CPU parallelism feature, reflected thread;

(2) thread has seven states:

1) New (New)

2) Runnable (run)

3) Running (running)

4) Blocked (blocked)

5) Waiting (waiting)

6) Timed waiting (waiting timer)

7) Timeinated (terminated)

Thread Status:

1) New threads:

new (New)

  Thread object just created, has not started, then the thread is still in the non-operational state. E.g:

  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接口的方法,比较了两种方法的优势。理论知识比较少,代码理解的也还可以。关于线程,这一周就了解了它的创建。还有线程的终止等需要掌握。编程练习对我来说很有挑战性,但还是会自己试着做一下的。

Guess you like

Origin www.cnblogs.com/-8tjj/p/12040214.html