201871010121- Wang Fang - "object-oriented programming java" Week 16 test summary

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/12031970.html

 

 

 

Job learning objectives

(1) master the Java application packaging operations;

(2) to grasp the concept of threads;

(3) master the two techniques threads created.

GUI (4) learning applications

The first section summarizes the basic experiment

First, what is the thread

(1) a program simultaneously perform multiple tasks, each task generally called a thread, the thread control is short. You can run more than one thread called multithreaded programs.

(2) each process has its own set of variables, two threads are sharing data.

(3) Java are two ways to achieve multi-threading:

        - create a subclass of the Thread class

        - define the implementation Runnable interface class in the program

(4) Windows system is a multi-tasking operating system, in order to process it as a unit. A process is a program that contains its own address, each program are called independent execution process, which is the program being executed.

Note: Remember thread and procedures are different, not to be confused

 (5) Since it is a multi-threaded operation, its work is characterized by: the system can allocate a limited period of execution of the CPU time for each process (also referred to as CPU time slice), CPU execute a process during this time, then the next time they jump to another process to execute. Since the speed of the CPU switches quickly, giving the user the feeling that these tasks seem to run simultaneously, so the use of multi-threading technology, can run more different kinds of tasks at the same time .

Second, the interrupt thread

  (1) In Java, the main mechanism to stop a thread is interrupted, the interrupt is not forced to terminate a thread, it is a cooperative mechanism, it is to pass a thread cancel signal, but to decide how and when to exit a thread.

(2) Thread class defines the following methods:

         public boolean isInterrupted (); indicates whether Tests if this thread has been interrupted. This method does not affect the interrupt status of the thread

         public void interrupt (); an interrupt thread

         public static boolean interrupted (); Indicates whether this thread has been interrupted test, and clears the interrupt flag

--interrupt way to represent interrupts the current thread, just set about the thread's interrupt flag.

--Interrupted is a static method, whether it will return the current thread interrupt bit is marked, if it returns true and clear the interrupt flag bit, otherwise false.

         public boolean isInterrupted() {

       return isInterrupted(false);}

--isInterrupted method function is similar to the interrupted process, but regardless of whether the current thread is interrupted, will not clear the interrupt flag.

      public static boolean interrupted() {

      return currentThread().isInterrupted(true);}

      private native boolean isInterrupted(boolean ClearInterrupted);

--interrupt () state influence on the threads and threads and performing IO operations related

   Third, the thread state

     RUNNABLE: threads are running or have run conditions just waiting for the operating system scheduler

     WAITING / TIMED_WAITING: thread waiting for some condition or timeout

     BLOCKED: threads wait for a lock, trying to get into sync blocks

     NEW / TERMINATED: thread has not started or has ended

(1) Create a new thread

       a. Use new Thread()to create a thread.

(2) runnable threads

      a. Use the Thread.start()following method. Start a thread, the thread enters execution queue waiting for the CPU, it can be broken down into runnable and running status.


(3) and the thread is blocked waiting threads

         A. difference between blocking and waiting for: the blocking is waiting to acquire an exclusive lock because the thread can not acquire lock so blocked and can not be allowed to live; waiting is waiting for some time or are waiting to be awakened, the state is not waiting waiting to acquire the lock.

This state has a feature, a lock request thread, then the thread enters the blocked state obtained; while another thread requests the lock again, due to the lack of blocked; when the lock is released, the blocked thread has the lock entered the running state . Also to know

The synchronizedmodified code blocks and methods. Between such parallel into serial execution threads.  

         B. waiting thread is divided into two cases, one is limited wait; the other is to wait indefinitely.

         C. Limited waiting: thread in this state, will not be assigned CPU execution time, you need to wait for the other thread explicitly resumed, then enter the running state.

            a. call Thread.join()method. We will have to wait on the end of a thread of execution, and then wake up on a thread.

            b. invoke Object.wait()methods. Will have to wait until the other thread using the notify (), notifyAll () wakes up.

        D. wait indefinitely: thread in this state, will not be assigned CPU execution time, other threads can either be explicitly resumed, may also wake up automatically by the system after a certain time, and then enter the running state.

           a. call Thread.sleep(timeout)method. This method does not release the held object lock.

           b. invoke Object.wait(timeout)methods. This method will release the locks held.

           c. calls the Thread.join(timeout)method.

(4) terminated thread: thread when run()the end of execution method, the thread ends.

Overall thread state as shown:

 

The second part of the experiment summary

Experiment 1:  introduction of the 13 Cap sample programs, test procedures and code comments.

Test Procedure 1

In elipse IDE commissioning textbook 585 page size of 13-1 , in conjunction with the results of running the program understanding;

The generated JAR file to a different directory further, the archive is run, the program is to confirm the resources, and not from the current directory is read from a JAR file.

l be able to create JAR method file;

ResourceTest

 

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;
   ResourceTestFrame public ()
   {
      the setSize (DEFAULT_WIDTH, DEFAULT_HEIGHT);
      the URL of aboutURL = getClass () getResource ( "about.gif");. // determine the target file, load the source code
      Image img = new ImageIcon (aboutURL) .getImage (); // settings icon
      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);  //添加到文件区域
   }
}

 

  Experimental results output screenshot:

 

 

 

 Detailed process is:

                     (Results again open as before)

 

 Test Procedure 2 :

In elipse IDE Debuging ThreadTest, combined result of the program be appreciated program;

grasp the concept of threads;

master by a method to implement threads of extension class Thread;

use Runnable Interface renovation program, with master Runnable method interface to create threads. 

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 Lefthands  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 Righthands  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 TheadTest01 {
         public static void main(String args[]) {
             Lefthands L=new Lefthands();
             Righthands R=new Righthands();
             
             new Thread(L).start();//启动线程
             new Thread(R).start();
     }
}

 实验输出结果截图为:

 可以通过两种方法实现多线程,分别为:(1)利用Thread类的子类(2)用Runnable()接口实现线程

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

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

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

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

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

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

 测试程序3

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

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

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

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

 bounce

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.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); }
}
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()); //start表示加入一个球
      addButton(buttonPanel, "Close", event -> System.exit(0));//系统退出
      add(buttonPanel, BorderLayout.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)
   {
      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)//中断异常
      {
      }
   }
}

 

 实验输出结果截图为:

 

 

 bounceThread

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;
   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 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 JComponent
{
   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 panel.
    * @param b the ball to add
    */
   public void add(Ball b)
   {
      balls.add(b);
   }

   public void paintComponent(Graphics g)
   {
      Graphics2D g2 = (Graphics2D) g;
      for (Ball b : balls)
      {
         g2.fill(b.getShape());
      }
   }
   
   public Dimension getPreferredSize() { 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
{
   private BallComponent comp;
   public static final int STEPS = 1000;
   public static final int DELAY = 5;


   /**
    * Constructs the frame with the component for showing the bouncing ball and
    * Start and Close buttons
    */
   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();
   }

   /**
    * 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 canvas and starts a thread to make it bounce
    */
   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();
   }
}

  实验输出结果截图为:

    

       通过对比可以发现bounce中的start按钮只能单次按钮,且前一次的小球的运动情况会影响大奥下一次的小球的进入。即只有当前一次进入运动轨迹的小球走完所有规定路线时下一个小球才可进入。而在bounceThread中灵活地应运了线程的知识,从而它的start键可以多次点击。同时引入多个小球同时运动且相互不影响。以至出现上图中我们在视觉上可以观察到的小球线性的运动轨迹。通过对比这也正是体现了线程的优点——提高系统资源利用率,改善系统性能。

第三部分  实验总结

       这周我们主要学习了线程的相关知识,其中多线程的定义联系我们生活中的实例会有助于我们理解。下按时生活中人们在解决问题都会考虑到效率性。我们的程序在解决问题时也一样。多线程就是一个典型的解决问题的方案。这种方法加快了我们解决问题的时间,极大地提高了效率。这些问题在理解上相对容易一些,但是在结对编程的过程当中还是会遇到很多问题,心里想的和做出来的往往差距很大。当然,这还是源于自己学习积累知识太少,所以以后我会更加努力地学习。

 

 

Guess you like

Origin www.cnblogs.com/wf-001128/p/12045785.html