zoukankan      html  css  js  c++  java
  • 201871010111-刘佳华《面向对象程序设计(java)》第十六周学习总结

    学号-姓名《面向对象程序设计(java)》第十六周学习总结

    实验十四  应用程序归档与线程初步

    实验时间 2019-12-12

    第一部分:理论知识总结

    1、程序与进程的概念

    程序是一段静态的代码,它是应用程序执行的蓝本。

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

    ‐操作系统为每个进程分配一段独立的内存空间和系统资源,包括:代码数据以及堆栈等资源。每 一个进程的内部数据和状态都是完全独立的。

    ‐多任务操作系统中,进程切换对CPU资源消耗较大。

    2、多线程的概念

    ‐多线程是进程执行过程中产生的多条执行线索。

    线程是比进程执行更小的单位

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

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

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

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

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

    ‐创建Thread类的子类

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

    4、用Thread类子类创建线程

    首先需从Thread类派生出一个子类,在该子类中重写run()方法。

    class hand extends Thread

    {

        public void run()

        {……}

    }

    5、用Thread类的子类创建多线程的关键性操作

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

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

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

    6、用Runnable()接口实现线程

    - 首先设计一个实现Runnable接口的类;

    - 然后在类中根据需要重写run方法;

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

    - 调用Thread类对象的start方法启动线程,将 CPU执行权转交到run方法。

    7、线程的终止

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

    - 调用interrupt()方法也可终止线程。

    void interrupt()

    – 向一个线程发送一个中断请求,同时把这个线程的“interrupted”状态置为true。

    – 若该线程处于 blocked 状态 ,会抛出 InterruptedException。

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

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

    -static boolean interrupted()

    – 检测当前线程是否已被中断 ,并重置状态 “interrupted”值为false。 

    -boolean isInterrupted()

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

    9、线程的状态

    -利用各线程的状态变换,可以控制各个线程轮流使用CPU,体现多线程的并行性特征。 

    -线程有如下7种状态:

    ➢ New (新建)

    ➢ Runnable (可运行)

    ➢ Running(运行)

    ➢ Blocked (被阻塞)

    ➢ Waiting (等待)

    ➢ Timed waiting (计时等待)

    ➢ Terminated (被终止)

    10、新创建线程

    -new(新建)

    线程对象刚刚创建,还没有启动,此时线程还处于不可运行状态。例如: Thread thread=new Thread(r); 此时线程thread处于新建状态,有了相应的内存空间以及其它资源。

    11、可运行线程

    - runnable(可运行状态)

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

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

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

    12、被阻塞线程和等待线程

    - blocked (被阻塞)

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

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

    ➢ 引起阻塞的原因很多,不同原因要用不同的方法解除。

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

    13、线程阻塞的三种情况

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

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

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

    14、被终止的线程

    Terminated (被终止) 线程被终止的原因有二:

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

    ➢ 二是因为一个没有捕获的异常终止了run方法而意外死亡。

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

    15、多线程调度

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

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

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

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

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

    第二部分:实验部分

    1、实验目的与要求

    (1) 掌握Java应用程序的打包操作;

    (2) 掌握线程概念;

    (3) 掌握线程创建的两种技术。

    2、实验内容和步骤

    实验1: 导入第13章示例程序,测试程序并进行代码注释。

    测试程序1

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

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

    掌握创建JAR文件的方法;

     1 package resource;
     2 
     3 import java.awt.*;
     4 import java.io.*;
     5 import java.net.*;
     6 import java.util.*;
     7 import javax.swing.*;
     8 
     9 /**
    10  * @version 1.41 2015-06-12
    11  * @author Cay Horstmann
    12  */
    13 public class ResourceTest
    14 {
    15    public static void main(String[] args)
    16    {
    17       EventQueue.invokeLater(() -> {
    18          JFrame frame = new ResourceTestFrame();
    19          frame.setTitle("ResourceTest");
    20          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    21          frame.setVisible(true);
    22       });
    23    }
    24 }
    25 
    26 /**
    27  * A frame that loads image and text resources.
    28  */
    29 class ResourceTestFrame extends JFrame
    30 {
    31    private static final int DEFAULT_WIDTH = 300;
    32    private static final int DEFAULT_HEIGHT = 300;
    33 
    34    public ResourceTestFrame()
    35    {
    36       setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
    37       URL aboutURL = getClass().getResource("about.gif");  //ip地址的路径地址,资源加载代码
    38       Image img = new ImageIcon(aboutURL).getImage();
    39       setIconImage(img);
    40 
    41       JTextArea textArea = new JTextArea();
    42       InputStream stream = getClass().getResourceAsStream("about.txt");
    43       try (Scanner in = new Scanner(stream, "UTF-8"))
    44       {
    45          while (in.hasNext())
    46             textArea.append(in.nextLine() + "
    ");//显示
    47       }
    48       add(textArea);
    49    }
    50 }
    ResourceTest

    运行截图:

     归档及之后运行截图:

       

       

    双击打开:

     

    测试程序2:

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

    l 掌握线程概念;

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

    利用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();

         }

    }

     源代码导入:

     1 package Thread;
     2 
     3 class Lefthand extends Thread { 
     4        public void run()
     5        {
     6            for(int i=0;i<=5;i++)
     7            {  System.out.println("You are Students!");
     8                try{   sleep(500);   }                //sleep(500);为定时等待500ms,sleep配合使用try-catch字句
     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("I am a Teacher!");
    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     }
    ThreadTest

    修改后代码:

     1 package Thread;
     2 
     3 class Lefthands  implements Runnable{
     4     public void run() {
     5         for(int i=0;i<=5;i++)
     6            {  System.out.println("You are Students!");
     7                try{   Thread.sleep(500);   }                
     8                catch(InterruptedException e)
     9                { System.out.println("Lefthand error.");}    
    10            } 
    11         
    12     }
    13     
    14 }
    15 class Righthands  implements Runnable{
    16     public void run() {
    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     
    26 }
    27 
    28 
    29 public class TheadTest01 {
    30         public static void main(String args[]) {
    31             Lefthands L=new Lefthands();
    32             Righthands R=new Righthands();
    33             
    34             new Thread(L).start();
    35             new Thread(R).start();
    36         }
    37 }
    TheadTest01 

    运行截图:(与源代码运行一致)

    测试程序3:

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

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

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

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

    p625 14.1-14.3程序:

     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)//Adds a button to a container.
    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()//在面板中添加一个弹跳球,使其弹跳1000次。
    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 }
    Bounce
     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); // 删除背景
    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.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;                           //x y方向上依次加位移增量
    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);
    54    }
    55 }
    Ball

     运行截图:

      

     14.4示例程序:

     1 package bounceThread;
     2 
     3 import java.awt.geom.*;
     4 
     5 /**
     6    A ball that moves and bounces off the edges of a 
     7    rectangle
     8  * @version 1.33 2007-05-17
     9  * @author Cay Horstmann
    10 */
    11 public class Ball
    12 {
    13    private static final int XSIZE = 15;
    14    private static final int YSIZE = 15;
    15    private double x = 0;
    16    private double y = 0;
    17    private double dx = 1;
    18    private double dy = 1;
    19 
    20    /**
    21       Moves the ball to the next position, reversing direction
    22       if it hits one of the edges
    23    */
    24    public void move(Rectangle2D bounds)//将球移动到下一个位置,如果碰到其中一个边,则反转方向
    25    {                                     //x y方向上依次加位移增量
    26       x += dx;
    27       y += dy;
    28       if (x < bounds.getMinX())
    29       { 
    30          x = bounds.getMinX();
    31          dx = -dx;
    32       }
    33       if (x + XSIZE >= bounds.getMaxX())
    34       {
    35          x = bounds.getMaxX() - XSIZE; 
    36          dx = -dx; 
    37       }
    38       if (y < bounds.getMinY())
    39       {
    40          y = bounds.getMinY(); 
    41          dy = -dy;
    42       }
    43       if (y + YSIZE >= bounds.getMaxY())
    44       {
    45          y = bounds.getMaxY() - YSIZE;
    46          dy = -dy; 
    47       }
    48    }
    49 
    50    /**
    51       Gets the shape of the ball at its current position.
    52    */
    53    public Ellipse2D getShape()
    54    {
    55       return new Ellipse2D.Double(x, y, XSIZE, YSIZE);
    56    }
    57 }
    Ball
     1 package bounceThread;
     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 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     * Add a ball to the panel.
    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       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  * 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 }
    BounceThread

     运行截图:

    实验2:结对编程练习:采用GUI界面设计以下程序,并创建程序归档文件。

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

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

    1)、整体编程思路:设计简单的布局情况实现对于小学生随机练习的功能实现,用到了简单的GUI页面布局管理,以及文件的读写操作。

     实验简单流程图:

         

    结对过程图片:

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

    代码如下:

     1 package TeamWork05;
     2 
     3 import java.awt.*;
     4 import java.awt.Image;
     5 
     6 import javax.swing.ImageIcon;
     7 import javax.swing.JFrame;
     8 
     9 public class CalculaterTest {
    10         public static void main(String args[]) {
    11             EventQueue.invokeLater(()->{
    12             JFrame frame =new CalculaterFrame();
    13             frame.setTitle("小学生练习题集  ");
    14             Image img=new ImageIcon("0.jpg").getImage();
    15             frame.setIconImage(img);
    16             frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    17             frame.setVisible(true);
    18             
    19         });
    20     }
    21 }
    CalculaterTest
      1 package TeamWork05;
      2 
      3 import java.awt.*;
      4 import java.awt.event.*;
      5 import java.io.*;
      6 import javax.swing.*;
      7 
      8 public class CalculaterFrame extends JFrame {
      9     private static final int WIDTH=500;
     10     private static final int HEIGHT=500;
     11     int i = 0, i1 = 0, k = 0, sum = 0;
     12     private PrintWriter out = null;
     13     private String[] c1 = new String[10];
     14     private String[] c2 = new String[10];
     15     
     16     public CalculaterFrame (){
     17         setSize(WIDTH, HEIGHT);
     18 
     19         setLayout(new GridLayout(3, 1));
     20         JPanel panelf =new JPanel();
     21         JTextField jt1 = new JTextField(15);
     22         jt1.setEditable(false);
     23         JTextField jt2 = new JTextField(8);
     24         JLabel jt3 = new JLabel();
     25         jt3.setText("■");
     26         
     27         panelf.add(new JLabel("题目:"));
     28         panelf.add(jt1);
     29         panelf.add(new JLabel("答题区:"));
     30         panelf.add(jt2);
     31         panelf.add(new JLabel("判断区:"));
     32         panelf.add(jt3);
     33         
     34         JPanel panel1 = new JPanel();
     35         JButton button1 = new JButton("开始");
     36         JButton button2 = new JButton("生成文件");
     37         JButton button3=new JButton("点击查看作答情况");
     38         panel1.add(button1);
     39         panel1.add(button2);
     40         panel1.add(button3);
     41         JTextArea Jt=new JTextArea(10,10);
     42         JScrollPane l=new JScrollPane(Jt);
     43         Jt.setEditable(false);
     44         this.add(panelf);
     45         this.add(panel1);
     46         this.add(l);
     47         
     48         button1.addActionListener(new ActionListener() {
     49            
     50             public void actionPerformed(ActionEvent e) {
     51                 button1.setText("下一题");
     52                 jt2.setText(null);
     53                 jt3.setText(null);
     54                 if (i < 10) {
     55                     int a = (int) (Math.random() * 100);
     56                     int b = (int) (Math.random() * 100);
     57                     int m = (int) Math.round(Math.random() * 3);
     58                     switch (m) {
     59                     case 0:
     60                         while (b == 0 || a % b != 0) {
     61                             b = (int) Math.round(Math.random() * 100);
     62                             a = (int) Math.round(Math.random() * 100);
     63                         }
     64                         jt1.setText("第"+(i+1)+"题:" + a + "/" + b + "=");
     65                         c1[i] = jt1.getText();
     66                         k = a / b;
     67                         i++;
     68                         break;
     69                     case 1:
     70                         jt1.setText("第"+(i+1)+"题:" + a + "*" + b + "=");
     71                         c1[i] = jt1.getText();
     72                         k = a * b;
     73                         i++;
     74                         break;
     75                     case 2:
     76                         jt1.setText("第"+(i+1)+"题:" + a + "+" + b + "=");
     77                         c1[i] = jt1.getText();
     78                         k = a + b;
     79                         i++;
     80                         break;
     81                     case 3:
     82                         while (a < b) {
     83                             int x = a;
     84                             a = b;
     85                             b = x;
     86                         }
     87                         jt1.setText("第"+(i+1)+"题:"  + a + "-" + b + "=");
     88                         c1[i] = jt1.getText();
     89                         k = a - b;
     90                         i++;
     91                         break;
     92                     }
     93                 }
     94             }
     95         });
     96         jt2.addActionListener(new ActionListener() {
     97 
     98             @Override
     99             public void actionPerformed(ActionEvent e) {
    100                 
    101                 if (i < 11) {
    102                     int find = Integer.parseInt(jt2.getText());
    103                     String d = jt2.getText().toString().trim();
    104                     if (jt2.getText() != "") {
    105                         if (find == k) {
    106                             sum += 10;
    107                             jt3.setText("✔");
    108                             jt3.setForeground(Color.green);
    109                         } else
    110                         { jt3.setText("✘");
    111                            jt3.setForeground(Color.red);}
    112                     }
    113                     c2[i1] = d;
    114                     i1++;
    115                 }
    116             }
    117         });
    118         button2.addActionListener(new ActionListener() {
    119 
    120             @Override
    121             public void actionPerformed(ActionEvent e) {
    122                 
    123                 try {
    124                     out = new PrintWriter("text.txt");
    125                 } catch (FileNotFoundException e1) {
    126                     // TODO Auto-generated catch block
    127                     e1.printStackTrace();
    128                 }
    129                 for (int counter = 0; counter < 10; counter++) {
    130                     out.println(c1[counter] + c2[counter]);
    131                 }
    132                 out.println("成绩为" + sum);
    133                 out.close();
    134             }
    135         });
    136         button3.addActionListener(e->{
    137             try {
    138                 File file = new File("D:\JAVA2\WEEK16\text.txt");
    139                 FileInputStream fis = new FileInputStream(file);
    140                 BufferedReader in = new BufferedReader(new InputStreamReader(fis,"UTF-8"));
    141                 String s = null;
    142                 while((s=in.readLine())!=null)
    143                 {
    144                     Jt.append(s+"
    ");
    145                 }
    146                 in.close();
    147             }catch (FileNotFoundException e1) {
    148                 System.out.println("文件未找到!");
    149                 e1.printStackTrace();
    150             } catch (IOException e1) {
    151                 System.out.println("文件打开错误!");
    152                 e1.printStackTrace();
    153             }
    154         });
    155     }
    156 }
    CalculaterFrame

    程序运行截图:

     

    单击开始开始答题;作答过程正误判断;

      

      

     下面对文件实施归档:

      

    在归档完成后桌面显示1.jar文件

     打开后为可以运行的jar程序:

    第三部分:实验心得体会

        多线程是进程执行过程中产生的多条执行线索。线程是比进程执行更小的单位。线程不能独立存在,必须存在于进程中,同一进程的各线程间共享进程空间的数据。每个线程有它自身的产生、存在和消亡的过程,是一个动态的概念。多线程意味着一个程序的多行语句可以看上去几乎在同一时间内同时运行。线程创建、销毁和切换的负荷远小于进程,又称为轻量级进程。

       本周了解到了线程以及线程两种创建方法,再次做一个比较:实现Runnable接口的优势:符合OO设计的思想;便于用extends继承其它类。采用继承Thread类方法的优点:代码简单。通过本周的结对编程,发现之前学的知识遗忘比较快,在文件读取这一块还是以往较严重,在之后还得看一下。

     

     

  • 相关阅读:
    课堂作业
    大道至简读后感
    读《大道至简》有感
    大道至简第四章-流于形式的沟通
    Java课堂动手动脑-截图集锦
    Java动手动脑课后作业1-求创建对象个数
    Java-消息框显示两整数加减乘除
    JAVA-实践问题
    Java-整数相加求和
    大道至简-是懒人造就了方法
  • 原文地址:https://www.cnblogs.com/JerryLau-213/p/12042051.html
Copyright © 2011-2022 走看看