201871010107-公海瑜《面向对象程序设计(java)》第十六周学习总结

          201871010107-公海瑜《面向对象程序设计(java)》第十六周学习总结

           项目                            内容
  这个作业属于哪个课程     https://www.cnblogs.com/nwnu-daizh/
  这个作业的要求在哪里   https://www.cnblogs.com/nwnu-daizh/p/12031970.html   
  作业学习目标

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

  (2) 掌握线程概念;

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

  (4) 学习设计应用程序的GUI。

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

1.线程的概念

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

创建线程的两种方法

方式1:继承java.lang.Thread类,并覆盖run()方法。              优势:编写简单;劣势:无法继承其他父类

方式2:实现java.lang.Runnable接口,并实现run()方法。       优势:可以继承其他类,多线程可以共享同一个Thread对象;

                                                                                          劣势:编程方式稍微复杂,如需访问当前线程,需调用Thread.currentThread()方法

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

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

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

多线程的概念:

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

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

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

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

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

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

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

‐创建Thread类的子类 ‐在程序中定义实现Runnable接口的类

2.中断线程

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

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

3.线程状态

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

线程有如下7种状态:

➢ New (新建)

    当创建Thread类的一个实例(对象)时,此线程进入新建状态(未被启动)。

    例如:Thread t1 = new Threade();

➢ Runnable (可运行)

    线程已经被启动(start),正在等待分配CPU时间片,也就是说此事线程正在就绪队列中排队等候得到CPU资源。

    例如:t1.start();

    运行(running)

    线程获得cpuz资源正在执行任务(run()方法),此时除非线程自动放弃CPU资源或者有优先级更高的的线程进入,线程将一直运行到结束!

➢ Running(运行)

➢ Blocked (被阻塞)

     由于某种原因导致正在运行的线程让出CPU并暂停自己的执行,即进入堵塞状态。

     正在睡眠:用sleep(long t) 方法可使线程进入睡眠方式。一个睡眠着的线程在指定的时间过去可进入就绪状态。

     正在等待:调用wait()方法。(调用notify()方法回到就绪状态)

     被另一个线程所阻塞:调用suspend()方法。(调用resume()方法恢复)

➢ Waiting (等待)

➢ Timed waiting (计时等待)

➢ Terminated (被终止)

  线程因如下两个原因之一而被终止:

  因为 run 方法正常退出而自然死亡。

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

  特别是,可以调用线程的 stop 方法杀死一个线程。该方法抛出 ThreadDeath 错误对象,由此杀死线程。但是, stop 方法已过时,不要在自己的代码中调用这个方法。

4.多线程调度

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

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

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

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

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

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

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

 

第二部分:实验部分

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

测试程序1

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

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

掌握创建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
{
   private static final int DEFAULT_WIDTH = 300;
   private static final int DEFAULT_HEIGHT = 300;

   public ResourceTestFrame()
   {  //返回类,并查找带有给定名称的资源。
      setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
      URL aboutURL = getClass().getResource("about.gif");
      Image img = new ImageIcon(aboutURL).getImage();
      setIconImage(img);
      //读取文件夹内容,写入到文本区中
      JTextArea textArea = new JTextArea();
      InputStream stream = getClass().getResourceAsStream("about.txt");
      try (Scanner in = new Scanner(stream, "UTF-8"))
      {
         while (in.hasNext())
            textArea.append(in.nextLine() + "\n");
      }
      add(textArea);  //添加到文件区域
   }
}

运行结果:

 

测试程序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();
     }
}

运行结果:

用Runnable接口改造程序后:

package thread;
class Lefthand implements Runnable {
    public void run() {
        for (int i = 0; i <= 5; i++) {
            System.out.println("You are Students!");
            try {
                Thread.sleep(500);  //休眠时间为500ms 
            } catch (InterruptedException e) {
                System.out.println("Lefthand error.");
            }
        }
    }
}

class Righthand implements Runnable {
    public void run() {
        for (int i = 0; i <= 5; i++) {
            System.out.println("I am a Teacher!");
            try {
                Thread.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) {
        Runnable left1 = new Lefthand();
        Runnable right1 = new Righthand() ;
        Thread left = new Thread(left1);
        Thread right = new Thread(right1);
        left.start();  
        right.start();
    }
}

运行结果:

 

测试程序3:

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

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

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;
   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)
   {
      x += dx;
      y += dy;
      if (x < bounds.getMinX())
      {
         x = bounds.getMinX();
         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()
   {
      return new Ellipse2D.Double(x, y, XSIZE, YSIZE);
   }
}
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
{
   private BallComponent comp;
   public static final int STEPS = 1000;
   public static final int DELAY = 3;

   /**
    * Constructs the frame with the component for showing the bouncing ball and
    * Start and Close buttons
    */
   public BounceFrame()
   {
      setTitle("Bounce");
      comp = new BallComponent();
      add(comp, BorderLayout.CENTER);
      JPanel buttonPanel = new JPanel();
      addButton(buttonPanel, "Start", event -> addBall());  //将按钮放入buttonPanel
      addButton(buttonPanel, "Close", event -> System.exit(0));
      add(buttonPanel, BorderLayout.SOUTH);  //将buttonPanel放入边界管理器的南端
      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)
   {  //生成按钮对象
      JButton button = new JButton(title);
      c.add(button);
      button.addActionListener(listener);   //注册监听器事件
   }

   /**
    * Adds a bouncing ball to the panel and makes it bounce 1,000 times.
    */
   public void addBall()
   {
      try
      {
         Ball ball = new Ball();
         comp.add(ball);

         for (int i = 1; i <= STEPS; i++)
         {
            ball.move(comp.getBounds());
            comp.paint(comp.getGraphics());
            Thread.sleep(DELAY);   //在两个球显示之间有延迟
         }
      }
      catch (InterruptedException e)  //中断异常
      {
      }
   }
}
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
{
   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)
   {
      balls.add(b);
   }

   public void paintComponent(Graphics g)
   {
      super.paintComponent(g); // erase background
      Graphics2D g2 = (Graphics2D) g;
      for (Ball b : balls)
      {
         g2.fill(b.getShape());
      }
   }
   
   public Dimension getPreferredSize() { return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT); }
}

运行结果:

      

程序14-4:

package bounceThread;

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

import javax.swing.*;

/**
    * 显示动画弹跳球
 * @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);
      });
   }
}

/**
 * 框架与球组件和按钮
 */
class BounceFrame extends JFrame
{
   private BallComponent comp;
   public static final int STEPS = 1000;
   public static final int DELAY = 5;


   /**
    * 用显示弹跳球以及开始和关闭按钮的组件构建框架
    */
   public BounceFrame()
   {
      comp = new BallComponent();
      add(comp, BorderLayout.CENTER);
      JPanel buttonPanel = new JPanel();
      addButton(buttonPanel, "Start", event -> addBall());
      addButton(buttonPanel, "Close", event -> System.exit(0));
      add(buttonPanel, BorderLayout.SOUTH);
      pack();
   }

   /**
              * 向容器添加按钮
    * @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)
   {
      JButton button = new JButton(title);
      c.add(button);
      button.addActionListener(listener);
   }

   /**
    * 在画布上添加一个弹跳球,并启动一个线程使其弹跳
    */
   public void addBall()
   {
      Ball ball = new Ball();
      comp.add(ball);
      Runnable r = () -> { 
         try
         {  
            for (int i = 1; i <= STEPS; i++)
            {
               ball.move(comp.getBounds());  //将球移动到下一个位置,如果碰到其中一个边缘则反转方向
               comp.repaint();    //重绘此组件。
               Thread.sleep(DELAY);   //在指定的毫秒数内让当前正在执行的线程休眠
            }
         }
         catch (InterruptedException e)
         {
         }
      };
      Thread t = new Thread(r);
      t.start();
   }
}

运行结果:

    

 

 

 

 

实验总结:

        这周学习了线程的定义及其线程的几个状态,对线程有了初步的认识及理解。课后通过实验实例更深入地了解了相关知识,做到了理论知识和实际应用相结合,但总体上来说有些方面还是不太懂,需要自己下去好好下功夫。

posted @ 2019-12-18 20:14  公海瑜-201871010107  阅读(203)  评论(1编辑  收藏  举报