201871010113- Liuxing Rui "object-oriented programming (java)" Week 16 learning summary

 

 

 

project

content

This work belongs courses

<Classroom teachers blog Home Links> https://www.cnblogs.com/nwnu-daizh/

Where this requirement in the job

<Job link address> 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.

(4) study design of the application GUI.

 

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

1. The concept of threads:

 Program is a piece of static code, which is modeled on the execution of the application.

 It is a dynamic process of implementation of the program, which corresponds to the load from the code, to perform a complete process is finished.

Multithreading is a number of clues to the implementation of a process's execution generated. A thread is executed smaller units than the process.

Thread can not exist independently, they 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.

( Route 2) Java Multiple Threads in two ways:

create a subclass of the Thread class

<1> to create threads using the Thread class subclass

First, the need to derive a subclass Thread class, override run () method in this subclass.
Example:
class Hand the extends the Thread

public void RUN ()
{......} 
}

<2> and then create objects of this subclass
Lefthand Lefthand Lefthand Lefthand new new left = ();
Righthand Righthand new new Righthand Righthand right = ();
<. 3> Finally start () method to start the thread
left.start ();
right.start ();

With the creation of critical operations multithreading Thread subclass: - define a subclass of the Thread class and implement user-threaded operation, namely 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. Implemented in a program defined in the Runnable interface class

( 2) with a Runnable () interface thread:

<1>  First, a design implemented class Runnable interface;
<2>  and needs to be rewritten in the class according to the run method;
<3> before creating the class object, this object is established as a parameter an object of the Thread class;
<4> call start method of the thread class object to start the thread, it will be forwarded to the CPU executes the right to run method.

2. Interrupt threads:

When ⚫ After 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.

⚫ call interrupt () method can terminate the thread.
interrupt void ()
- send an interrupt request to a thread, while the "interrupted" state of the thread is set to true.
- If the thread is blocked state, it will throw InterruptedException.

( Method 2) whether the test thread is interrupted

Java provides several methods used to test whether the thread is interrupted.
Static boolean interrupted ⚫ ()
- detects whether the current thread has been interrupted and reset state "interrupted" is false.
Boolean isInterrupted ⚫ ()
- detects whether the current thread has been interrupted, does not change the state "interrupted" value.

3. Thread Status:

State transition by each thread, each thread turn can be used to control the CPU, embodies multi-threaded parallelism characteristics.
⚫ thread has the following seven states:
➢ New (New)

⚫ new (new)
thread object just created, 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.

➢ Runnable (run)

⚫ 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 ();

➢ Running (running)

➢ Blocked (blocked)

⚫ blocked (blocked)
threads being executed ➢ a 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, different reasons to use different methods to lift.
⚫ sleep (), wait () method are two common causes threads blocked.

➢ Waiting (waiting)

⚫ waiting blocking - by calling the thread wait () method, thread to wait for the completion of a job.

➢ Timed waiting (waiting timing)
➢ Terminated (terminated)

There are two reasons ⚫ Terminated (terminated) thread is terminated:
➢ First run () method in the last statement is finished and died of natural causes.
➢ a second, because there is no capture of aborted the run method and accidental death.
➢ 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.

Other methods of determining the impact and thread state

➢join (): wait for termination of the specified thread.

➢join (long millis): Specifies the time to wait after termination of the specified thread.
➢isAlive (): test whether the current thread activity.
➢yield (): Let the current thread "running state" into a "ready state" so that other waiting threads with the same priority access to executive power.

4. Multi-thread scheduling:

- 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.
- is runnable threads of the first to enter 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.

⚫ Java thread scheduling uses priority policies:
➢ first implementation of high priority, low priority after execution;
➢ When a multi-threaded system will automatically assign a priority to each thread by default, inherit the priority of the parent class level;
➢ mission-critical threads, the higher priority;
➢ the same priority thread queue according to the principle "first in first out" of;

⚫ under the following situations, the currently running thread will give up the CPU:
- thread calls yield () or sleep () method;
- under preemptive system, high-priority thread scheduling involved;
- Due to the current thread for I / O access, external memory read and write, waiting for user input and other operations led to thread blocked; or is waiting for a condition variable, and thread calls wait () method.

Concurrent execution of multiple threads in question:

◆ relative order of execution of multiple threads is uncertain.
◆ thread execution order uncertainty create uncertainty in the results.
◆ often generate this uncertainty in a multi-threaded operations on shared data.

5. Thread Synchronization:

Multi-threaded run concurrently uncertainties solution: the introduction of thread synchronization mechanism, so that another thread To use this method, you can only wait.

Part II: Experimental part

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 Chapter 13 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 comments below

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);
      
      // make use about.gif image file icon
      URL aboutURL = getClass () getResource ( "about.gif");. // URL getResource (String name) to find the resources and the classes are in the same position, the return can load a resource URL
      Image img = new ImageIcon(aboutURL).getImage();
      setIconImage(img);

      // Read about.txt file
      JTextArea textArea = new JTextArea();
      InputStream stream = getClass () getResourceAsStream ( "about.txt");. // InputStream getResourceAsStream (String name), returns a resource can load input stream
      try (Scanner in = new Scanner(stream, "UTF-8"))
      {
         while (in.hasNext())
            textArea.append(in.nextLine() + "\n");
      }
      add(textArea);
   }
}

 Run as shown:

Archiving:

Summary: resources mechanism, the step for the non-class file operations: 1) obtaining a Class object with resources 2) If the resource is an image or a sound file, then the need to call getresource (filename) is obtained as a resource position of the URL, and then use getAudioClip getImage method or read. 3) different image or sound files, other resources can be used to read the data file getResourceAsStream method.

Test Procedure 2:

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

l grasp the concept of threads;

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

Use Runnable Interface renovation program, with master method Runnable 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();
     }
}

注释代码如下:

package a;

	//构建Thread类的子类定义线程
	class Lefthand extends Thread { 
	   public void run()
	   {
	       for(int i=0;i<=5;i++)
	       {  System.out.println("You are Students!");
	           try{   
	        	   sleep(500); //暂停,每0.5秒输出一次 
	           }
	           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();//启动这个线程,引发调用run()方法。立即返回,新线程并发运行
	           right.start();
	     }
	}

运行结果如图:

利用Runnable接口改造程序如下:

package a;
import javax.print.attribute.standard.RequestingUserName;
class Lefthand implements Runnable { 
       public void run()
       {
           for(int i=0;i<=5;i++)
           {  System.out.println("You are Students!");
               try{  Thread.sleep(500);   }
               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)
         {   //  left=new Lefthand();
               //right=new Righthand();
            
               Runnable lefthand=new Lefthand();
               Thread left=new Thread(lefthand);// Runnable没有start这个方法,需要将Runnable的对象被Thread引用才可在Thread中调用start方法
                
            
               Runnable righthand=new Righthand();
               Thread right=new Thread(righthand);
               left.start();
               right.start();
         }
    }

测试程序3:

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

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

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

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

 Ball.java:

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);
   }
} 

BallComponent.java:

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 JComponent
{
   private static final int DEFAULT_WIDTH = 450;
   private static final int DEFAULT_HEIGHT = 350;

   private java.util.List<Ball> balls = new ArrayList<>();//构造一个初始容量为 10 的空列表。
//此接口的用户可以对列表中每个元素的插入位置进行精确地控制。用户可以根据元素的整数索引(在列表中的位置)访问元素,并搜索列表中的元素。
   /**
    * 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); }
}
  

BounceFrame.java:

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);//将自建的swing组件放在居中的位置
      JPanel buttonPanel = new JPanel();
      addButton(buttonPanel, "Start", event -> addBall());
      addButton(buttonPanel, "Close", event -> System.exit(0));//将两个组件注册为事件源并添加到buttonpanel中
      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);
   }//用addbutton方法将两个按钮组合为一个整体

   /**
    * 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);//调用sleep并未创建线程对象,只是为了将两个球的轨迹可以显示出来
         }
      }
      catch (InterruptedException e)
      {
      }
   }
}

BounceFrame.java:

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();//使得小球的移动成为其中的一个子线程
   }
}

运行结果如图:

开始截图:

 

未改进代码截图:

改进后的截图:

小结:两个程序的不同之处在于:第一个程序存在一定的缺陷,在该程序中,小球的运动轨迹的显示只是程序的一部分,当点击start开始后,在程序运行过程中,即显示小球运动轨迹过程中,并不能通过close或者右上角的关闭界面键来关闭程序;第二个程序是对第一个程序的缺陷进行了优化,它将小球的显示轨迹创建为程序的一个子线程,这样在小球显示轨迹过程中,可随时关闭界面。

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

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

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

实验总结:

通过本周的学习我学到了线程的概念,并且掌握了线程创建的两种技术,(1)用Thread类的子类创建线程(2)用Runnable()接口实现线程;

理解和掌握了线程的优先级属性及调度方法,学到了线程的七种状态。

 

Guess you like

Origin www.cnblogs.com/lxr0/p/12034340.html