201871010123- Wu Lili "object-oriented programming (Java)" Week 16 learning summary

                                                                                  201871010123- Wu Lili "object-oriented programming (Java)" Week 16 learning 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.

(Four) study design application GUI.

Part I: summary of the intellectual content of textbooks 14.1-14.3

1, procedures and processes concept:

(1) program is a piece of static code, which is modeled on the execution of the application.

(2) process is a dynamic program execution, which corresponds to the load from the code, to perform a complete process is finished.

(3) The operating system allocates memory space and a separate piece of system resources for each process, comprising: a stack code data and other resources. Internal data and the status of each process is completely independent.

(4) multi-tasking operating system, the process of switching to a larger CPU resource consumption.

2, multi-threading concepts:

 

(1) is a multi-threaded implementation of a number of clues execution process produced.

(2) execution threads are smaller units than the process.

(3) threads can not exist independently, they must exist in the process, among threads of the same process of data sharing process space.

(Four) Each thread has its own production, and the presence of dying out, is a dynamic concept.

Multi-line statement (5) means a multi-threaded program can run simultaneously looked almost at the same time.

(6) thread creation, destruction and load switching is much smaller than the process, also known as lightweight processes (lightweight process).

3, Java multi-threaded in two ways:
(1) create a subclass of the Thread class

(2) defining class implements Runnable interface in the program

4, create a thread with the Thread subclass:

(1) first need a class derived from Thread subclass, override run () method in this subclass. 

class hand extends Thread { 
public void run() {……}
}

(2) then create objects of the subclass 

Lefthand left=new Lefthand(); 
Righthand right=new Righthand(); 

(3) Finally, start () method to start a thread 

left.start(); 
right.start();

 

5, create critical operations with multi-threaded Thread subclass:

(1) the definition of a subclass of class Thread operation and implement user threads that run implement () method.

(2) start the thread at the appropriate time.

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

6, with Runnable () interface thread

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

(2) is then run in the class method needs to be rewritten; 

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

start method (4) calls the Thread class object of starting a thread, will be forwarded to the CPU executes the right to run method.

 

E.g:

class A implements Runnable{ 
public void run(){….} 
} 
class B { 
    public static void main(String[] arg){
         Runnable a=new A(); 
         Thread t=new Thread(a);
         t.start(); 
         }
}

 

7, the thread termination

(1) When the execution method body run method of the thread in the last statement, or there has been an exception in the run method does not capture the thread will terminate, so that the CPU usage rights.

(2) call interrupt () method can terminate the thread.

          -----void interrupt()

(3) sends an interrupt request to a thread, while the "interrupted" state of the thread is set to true.

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

8, if the test was interrupted thread method

(1) Java provides several methods for testing whether a thread is interrupted.

       -static boolean interrupted()

If (2) detects the current thread has been interrupted, and reset the state "interrupted" is false. 

       -boolean isInterrupted()

If (3) detects the current thread has been interrupted, it does not change the state "interrupted" value.

9, the state of the thread:

(1) by each state transition of threads, each thread may be controlled using the CPU in turn, reflect the characteristics of multi-threaded parallelism. 

(2) thread has the following seven states: 

➢ New (New)

➢ Runnable (run)

➢ Running (running)

➢ Blocked (blocked)

➢ Waiting (waiting)

➢ Timed waiting (waiting timer)

➢ Terminated (terminated)

10, the newly created thread

 new (New)

      ----- thread object just created, it has not started, then the thread is still in the non-operational state. For example: Thread thread = new Thread (r); in this case a new thread the thread state, with the corresponding memory space and other resources.

11, runnable threads

- runnable (runnable)

➢ thread has been started at this time, among the methods in the thread run ().

➢ threads may be running at this time, or may not run as long as a CPU is idle, it will soon run.

➢ calling thread's start () method allows the thread is "runnable" state. For example: thread.start ();

12, and the thread is blocked waiting threads

 

- blocked (blocked)

➢ a thread being executed due to special reasons, be suspended into the blocked state.

➢ When blocked thread can not enter the queue line up, must wait until the causes obstruction to eliminate before they can re-enter the queue line.

➢ obstruction caused by many reasons, use different methods for different reasons lift.

-sleep (), wait () is a method commonly caused by two threads blocked.

13, thread blocked three cases:

(1) wait for blocking: () method wait by the calling thread, so thread waits for completion of a job. 

(2) synchronous blocking: get synchronized thread synchronization lock failure (because the lock was occupied by another thread), it will enter synchronous blocking state. 

(3) Other blocking: The sleep () or join the calling thread () or issued I / O request, the thread into the blocked state. When sleep () timeout, the Join () or a timeout wait for a thread to terminate, or I / O processing is completed, the thread into the ready state again.

14, is terminated thread

 There are two reasons (1) Terminated (terminated) thread is terminated: 

      a. First run () method in the last statement is finished and died of natural causes. 

      b. a second, because there is no capture of aborted the run method and accidental death. 

   (2) the thread can call the stop method to kill a thread (thread.stop ();), however, stop method is obsolete and do not call it in your own code.

15, judgment and affect other thread state methods:

(1) join (): wait for the specified thread terminates. 

(2) join (long millis): Specifies the time to wait after termination of the specified thread. 

(3) isAlive (): test whether the current thread activity. 

(4) yield (): Let the current thread "running state" into a "ready state", so that other waiting threads with the same priority access to executive power.

16, multi-thread scheduling

(1) Java provides a thread scheduler to monitor all threads started the program after entering the runnable state. In accordance with the priority of the thread scheduler decides thread which threads should be scheduled for execution.

Thread (2) in a runnable state first enters the ready queue waiting processor resources, the same time the thread in the ready queue may have multiple. Java multi-threaded system will automatically assign a priority to each thread a thread.

 17, Java thread scheduling uses priority policies:

(1) to perform a higher priority, low priority after execution;

(2) multi-threaded system is automatically assigned a priority, default, its superclass inherit the priority of each thread;

(3) emergency task threads, the higher priority;

(4) the same priority thread by "FIFO" queue principle;

18, daemon thread

(1) Use only the guardian of the thread is to provide services to other threads. For example, the timing thread.

(2) Before a thread is started, call setDaemon method to convert a thread as a daemon thread (daemon thread). For example: setDaemon (true);

19, Thread class has three static and thread priorities related to the amount of:

➢ MAX_PRIORITY: the highest priority, is 10;

➢ MIN_PRIORITY: minimum priority value is 1;

➢ NORM _PRIORITY: default priority value is 5.

Part II: Experimental part                                      

Experimental fourteen applications filed with the preliminary thread 

Experimental time 201 . 9 -1 2 - 12 is

1 , experimental purposes and requirements

(1) master the Java application packaging operations;

(2) to grasp the concept of threads;

(3) master the two techniques threads created.

2 , experimental and step

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.

 

be able to create JAR method file;

 Code is as follows:

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 long serialVersionUID = 1L;
private static final int DEFAULT_WIDTH = 300;
   private static final int= DEFAULT_HEIGHT 300 ; 

   public ResourceTestFrame () 
   { 
      the setSize (DEFAULT_WIDTH, DEFAULT_HEIGHT); 
      the URL aboutURL = getClass () the getResource (. " About.gif " ); // find the file in the getResourse getclass about.gif method 
      . The System OUT .println (aboutURL); 
      image img = new new ImageIcon (aboutURL) .getImage (); // use about.gif image file creation icon 
      setIconImage (img); 

      JTextArea textArea = new new JTextArea (); // create a textArea objects 
      InputStream stream = getClass () .getResourceAsStream ( "about.txt");//读取about.txt文件
      try (Scanner in = new Scanner(stream, "UTF-8"))
      {
         while (in.hasNext())
             textArea.append(in.nextLine() + "\n");
      }
      add(textArea);
   }
}

Results are as follows:

 

Step manner using the Eclipse jar file export:

Select ResourceTest ----> Right, Export ...----> Java ----> JAR file ----> next ----> Enter Resource.jar in the text area of ​​the JAR file ----> next ----> next ----> select the Main class ----> Finish.

 The exported file as follows:

 Double-click Resourse.jar appeared after the following pages:

 

 

 

Test Procedure 2 :

 

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

 

掌握线程概念;

 

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

 

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

ThreadTest.java代码如下:

 

class Lefthand extends Thread { 
   public void run()
   {
       for(int i=0;i<=5;i++)
       {  System.out.println("You are Students!");
           try{   sleep(500);   }    //用了sleep()方法,休眠500毫秒
           catch(InterruptedException e)
           { System.out.println("Lefthand error.");}    
       } 
  } 
}
class Righthand extends Thread {
    public void run()     //重写run方法
    {
         for(int i=0;i<=5;i++)
         {   System.out.println("I am a Teacher!");
             try{  sleep(300);  }     //用了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接口改造的程序如下:

 

class Lefthand implements Runnable{             //用Runnable()接口实现线程
   public void run()
   {
      
       for(int i=0;i<=5;i++)
       {  System.out.println("You are Students!");
           try{ Thread.sleep(500);   }    //调用了Thread类的start方法
           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 Thread1
{
     static Lefthand left;
     static Righthand right;
     public static void main(String[] args)
     {      //创建Runnable类型的对象,以此类对象为参数建立Thread类的对象
           Runnable lefthand = new Lefthand();    
           Thread left=new Thread(lefthand);    
            left.start();              //调用left这个对象变量的start方法
            Runnable righthand = new Righthand();
            Thread right=new Thread(righthand);
              right.start();  
     }
}

 

运行结果如下:

测试程序3

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

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

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

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

Bounce.java代码如下:

 

package bounce;

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

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

/**
 * 带有球组件和按钮的框架。
 */
class BounceFrame extends JFrame
{
   private BallComponent comp;
   public static final int STEPS = 1000;
   public static final int DELAY = 3;

   /**
    * 使用组件构造框架,以显示弹跳球和开始和关闭按钮
    */
   public BounceFrame()
   {
      setTitle("Bounce");
      comp = new BallComponent();    //创建一个新的BallComponent类赋给comp
      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容器
    * @param 按钮标题
    * @param 侦听器按钮的操作侦听器
    */
   public void addButton(Container c, String title, ActionListener listener)
   {
      JButton button = new JButton(title);
      c.add(button);
      button.addActionListener(listener);
   }

   /**
    * 向面板中添加一个弹跳球,使其弹跳1000次。
    */
   public void addBall()
   {
      try
      {
         Ball ball = new Ball();
         comp.add(ball);

         for (int i = 1; i <= STEPS; i++)
         {
            ball.move(comp.getBounds());      //调用ball这对象变量来移动球
            comp.paint(comp.getGraphics());   //调用comp的paint方法来绘画
            Thread.sleep(DELAY);       //调用Thread类的sleep方法
         }
      }
      catch (InterruptedException e)
      {
      }
   }
}

 

BallComponent.java代码如下:

 

package bounce;

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

/**
 * 画球的部件。
 * @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<>();

   /**
    * 向组件添加一个球。
    * 要添加的球
    */
   public void add(Ball b)
   {
      balls.add(b);
   }

   public void paintComponent(Graphics g)
   {
      super.paintComponent(g); // 擦除背景
      Graphics2D g2 = (Graphics2D) g;
      for (Ball b : balls)   //foreach循环
      {
         g2.fill(b.getShape());   //通过对象变量b的getShape方法来传参给fill
      }
   }
   
   public Dimension getPreferredSize() { return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT); }     //通过返回一个新建Dimension类来获取组件的大小
}

 

Ball.java代码如下:

 

package bounce;

import java.awt.geom.*;

/**
 * 从长方形边缘上移动和弹跳的球
 * @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;

   /**
    * 将球移动到下一个位置,如果球碰到其中一条边,则反向移动
    */
   public void move(Rectangle2D bounds)
   {
      x += dx;
      y += dy;
      if (x < bounds.getMinX())  //通过bounds来获得宽度的最小值
      {
         x = bounds.getMinX();
         dx = -dx;
      }
      if (x + XSIZE >= bounds.getMaxX())    //通过bounds来获得宽度的最大值
      {
         x = bounds.getMaxX() - XSIZE;
         dx = -dx;
      }
      if (y < bounds.getMinY())    //通过bounds来获得高度的最小值
      {
         y = bounds.getMinY();
         dy = -dy;
      }
      if (y + YSIZE >= bounds.getMaxY())   //通过bounds来获得高度的最大值 
      {
         y = bounds.getMaxY() - YSIZE;
         dy = -dy;
      }
   }

   /**
    * 获取球在当前位置的形状。
    */
   public Ellipse2D getShape()
   {
      return new Ellipse2D.Double(x, y, XSIZE, YSIZE);      //用Ellipse2D类绘制圆作为返回值
   }
}

 

运行结果如下:

 

 该程序的close键不可用,点击没反应

后将Bounce.java通过线程来修改,其程序为BounceThread.java来修改后,close可使用了

BounceThread.java代码如下:

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);     //将comp添加到边框布局的中间
      JPanel buttonPanel = new JPanel();
      addButton(buttonPanel, "Start", event -> addBall());
      addButton(buttonPanel, "Close", event -> System.exit(0));
      add(buttonPanel, BorderLayout.SOUTH);
      pack();
   }

   /**
    * 将按钮添加到容器中。
    * @param c容器
    * @param 按钮标题
    * @param 侦听器按钮的操作侦听器
    */
   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);       //向comp中添加球
      Runnable r = () -> {       //Runnable是函数式接口,用lambda表达式
         try
         {  
            for (int i = 1; i <= STEPS; i++)
            {
               ball.move(comp.getBounds());   //将comp的getBounds方法作为参数来传递ball的move方法
               comp.repaint();           //通过对象来调用repaint方法,repaint方法是在另外一个绘制线程里进行的
               Thread.sleep(DELAY);   //通过Thread线程来调用sleep方法
            }
         }
         catch (InterruptedException e)
         {
         }
      };
      Thread t = new Thread(r);    //创建一新的线程
      t.start();    //调用start方法来启动线程
   }
}

 

运行结果如下:

 

 按了close按钮后就关闭程序了,该程序与前一个程序的不同是:这个体现了线程的并发性,其点一次Start就出现一个球,而前一个程序不管你点多少次start,都有等到第一个工作完之后才可运行,所以该程序很好的体现了线程的特点。

 

 

实验总结:

在本次实验中进行第一个实验时,刚刚开始不知道怎么将jar文件导出来,后通过网上查询知道了如何去导出来,在该实验中也了解到了有关线程的概念和用途,学会了线程的创建方法,理解了线程优先级属性及调度方法,同时通过测试程序三能够很好的认识到了线程的特点。

Guess you like

Origin www.cnblogs.com/lily-2018/p/12043649.html