Week 16 learning summary

Bowen beginning of the text format: (2 points)

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

In this chapter:

14.1 What is the thread

1. process - concept

To explain the thread, it is necessary to understand what is the process.

What is the process?

    Process is an application running, each process has its own separate address space (memory), such as the user clicks on the desktop IE browser, you start a process, the operating system for the process to allocate separate address space. When the user clicks again left the IE browser, it has launched a process, the operating system will assign a new separate address space of the new process. Currently operating systems support multiple processes.

Important: each user starts a process, the operating system will allocate a separate memory space for that process.

2. Thread - concept

After realizing the process, it is easier to understand the concept of threads.

What is the thread of it?

    Is a physical process, is the basic unit of independent scheduling and dispatch system, the thread does not own its own system resources, it has only a little in the operation of essential resources, but it may belong to the same process with the other threads share the process It has all the resources. A thread can create and undo another thread can execute concurrently across multiple threads in the same process. There are threads ready, blocking and run three basic states.

3. Thread

1, the thread is a lightweight process

2, the thread does not separate address space (memory space)

3, the thread is created by the process (parasites in the process)

4, a process can have multiple threads -> this is what we often say that the multi-threaded programming

5, the thread in several states:

  a, the new state (new)

  b, ready state (Runnable)

  c, the operating state (Running)

  d, blocked (Blocked)

  e, death state (Dead)

4. What is the use of threads

java program to spread the word, do not use threads do not tell other people say they learned java. At present, most applications will involve the issue of multiple concurrent. As long as the application involves concurrent, multithreaded programming can not be separated.

5. Thread - How to use

In java class to be used as a thread to use in two ways.

1, inheritance Thread class and override the run function

2, implement Runnable, and override the run function

Because java is single inheritance, in some cases, a class may have inherited a parent class, then obviously impossible to create a thread in java designers provides another way to create threads inheritance Thread class method, that is, to create a thread by implementing Runnable interface.

14.2 interrupt thread

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

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

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

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

Other judgments and influence the state of the thread method:

(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.

14.3 Thread States

Java threads in the state is divided into six kinds.

1. Initial (NEW): create a new thread object, but has not been called start () method.
2. Run (RUNNABLE): Java thread will be ready (ready) and running (running) two states generally referred to as "run."
After the thread object is created, other threads (such as main thread) calls the start () method of the object. The thread state is located runnable threads in the pool, waiting to be selected thread scheduling, acquiring the right to use the CPU, this time in a ready state (ready). Ready state after obtaining thread CPU time slice becomes operational status (running).
3. blocked (BLOCKED): means the thread is blocked in the lock.
4. Wait (WAITING): This state is entered threads need to wait for other threads to make some specific action (notification or interrupt).
The time-out period (TIMED_WAITING): This state is different WAITING, it can return itself after a specified time.
6. Termination (TERMINATED): the thread has finished.

These six states are defined in the enumeration Thread class State, may be one-source view.

Thread state diagram     

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:  introducing 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.

掌握创建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");//找到指定位置的图像文件,返回一个可以加载资源的URL
      Image img = new ImageIcon(aboutURL).getImage();//将加载的about.gif图像设置为图标
      setIconImage(img);
 
      JTextArea textArea = new JTextArea();
      InputStream stream = getClass().getResourceAsStream("about.txt");//读取about.txt文本文件内容
      try (Scanner in = new Scanner(stream, "UTF-8"))//将读取到的about.txt文本文件里内容显示到文本区
      {
         while (in.hasNext())//读取文本文件
            textArea.append(in.nextLine() + "\n");
      }
      add(textArea);
   }
}
复制代码

 

 归档:

 

 

 

 

实验1:测试程序2(10分)

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

掌握线程概念;

掌握用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 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:

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

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

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

 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.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();
   }
}
复制代码

实验输出结果截图为:

 

 实验总结:

此课程在本学期学习中,前期问题教多,作为计算机专业学生,前提课程Java程序设计必不可少,没有良好的编程能力作为基础,此课程进行中,困难重重。但是在后期,不管我们每个人学习情况如何,我们基本对这些问题解决掉了,取长补短,达到了平衡状态。

 

Guess you like

Origin www.cnblogs.com/G19990718/p/12063552.html