201871010121- 왕 송곳니 - "객체 지향 프로그래밍 자바"주 16 테스트 요약

계획

함유량

이 작품은 과정 속

https://www.cnblogs.com/nwnu-daizh

어디에서 작업이 요구 사항

https://www.cnblogs.com/nwnu-daizh/p/12031970.html

 

 

 

작업 학습 목표

(1)는 Java 애플리케이션 패키징 작업 마스터;

(2) 스레드의 개념을 파악하는 단계;

(3) 마스터 두 기법 스레드 만들었다.

GUI (4) 학습 애플리케이션

첫 번째 섹션은 기본적인 실험을 요약

첫째, 실 것입니다

(1) 프로그램은 동시에 여러 작업을 수행하는 각 작업은 일반적으로 스레드 제어 짧은 스레드했다. 당신은 하나 개의 스레드 멀티 스레드 프로그램을 호출보다 더 실행할 수 있습니다.

(2) 각각의 프로세스 변수의 자신의 세트를 갖는 두 개의 스레드가 데이터를 공유한다.

(3) 자바는 멀티 스레딩을 달성하는 방법은 두 가지가 있습니다 :

        - Thread 클래스의 서브 클래스를 생성

        - 프로그램에 구현 된 Runnable 인터페이스 클래스를 정의

(4) 윈도우 시스템 단위로 처리하기 위해, 멀티 - 태스킹 운영 체계이다. 프로세스는 실행되는 프로그램이며, 각 프로그램은 독립 실행 처리라고 자신의 주소를 포함하는 프로그램이다.

참고 : 스레드를 기억 및 절차,하지 혼동 다른

 (5)는 작업이 특징으로, 멀티 스레드 동작이므로 : 시스템의 각 처리 (도 CPU의 타임 슬라이스라고 함), CPU는이어서,이 시간 동안 처리를 실행하기 위해 CPU 시간의 실행 제한 시간을 할당 할 수있다 그들은 다른 프로세스로 이동 다음 번에 실행합니다. CPU의 속도는 이러한 작업을 동시에 실행하는 것처럼 보인다 멀티 스레딩 기술의 사용이 동시에 작업의 많은 다른 종류를 실행할 수 있도록, 사용자에게 느낌을주는, 빠르게 전환 이후 .

둘째, 인터럽트 스레드

  (1)에서 자바 스레드를 중지하는 주요 메커니즘이 중단되고, 인터럽트가 스레드를 통과 신호를 취소하지만, 언제, 어떻게 스레드를 종료하는 방법을 결정하는 것입니다, 그것은 협력 메커니즘, 스레드를 강제로 종료되지 않습니다.

(2) Thread 클래스는 다음과 같은 방법을 정의한다 :

         공공 부울 isInterrupted은 ();이 스레드가 중단 된 경우 테스트 여부를 나타냅니다. 이 메소드는 thread의 인터럽트 상태에 영향을주지 않습니다

         공공 무효 인터럽트 () 스레드 인터럽트

         공공 정적 부울 중단 (는)이 스레드 인터럽트 테스트했는지 여부를 나타내는 인터럽트 플래그를 클리어

현재의 thread에 인터럽트를 대표하는 --interrupt 방법은, 바로 스레드의 인터럽트 플래그에 대해 설정합니다.

--Interrupted는,이 true를 돌려주는 경우, 비트 인터럽트 현재의 thread가 표시되어 반환하고 인터럽트 플래그 비트를 지우 여부, 정적 방법이다 , 그렇지 않은 경우는 false.

         공공 부울 isInterrupted () {

       반환 isInterrupted ( 거짓); }

--isInterrupted 방법 기능은 중단 된 프로세스와 유사하지만,에 관계없이 현재의 thread가 중단 여부, 인터럽트 플래그를 지우하지 않습니다.

     공공 정적 부울 중단 () {

      . currentThread () isInterrupted (반환 TRUE); }

      개인 기본 부울 isInterrupted ( ClearInterrupted 부울);

관련 스레드를 스레드 실행 및 IO 동작에 --interrupt () 상태의 영향

   셋째, 스레드 상태

     RUNNABLE는 : 스레드 실행하거나 운영 체제 스케줄러 대기 조건을 실행 한

     대기 / TIMED_WAITING : 스레드가 어떤 조건 또는 제한 시간을 기다리고

     차단됨 : 스레드가 동기화 블록으로 얻으려고, 잠금 대기

     NEW는 / 종료되었습니다 : 스레드가 시작되지 않았거나 종료

(1) 새로운 스레드를 만듭니다

       가. 사용 new Thread()스레드를 만들 수 있습니다.

(2) 실행 가능한 스레드

      가. 사용 Thread.start()다음과 같은 방법을. 스레드를 시작, 스레드가 CPU의 실행 큐 대기에 진입, 그것은 실행 가능한 실행 상태로 나눌 수 있습니다.


(3) 스레드가 대기 스레드 차단

         차단과 대기 사이 A. 차이 : 차단 스레드가되지 취득 잠금 때문에 차단 할 수 있기 때문에 배타 잠금을 획득하려고 대기하는 라이브 허용 될 수 없다 기다리는 시간을 기다리고이나 깨어날 수 기다리고 있습니다 상태는 대기하지 않습니다 락의 취득을 대기.

다른 스레드에 의한 차단이 부족하여, 다시 로크를 요청하면서, 상기 잠금이 해제되면, 차단 된 스레드가 잠금이 실행 상태에 들어간 상태는 특징 로크 요청 스레드 다음 스레드 얻어진 차단 상태 진입을 갖는다 . 또한 알고

synchronized코드 블록과 방법을 수정했습니다. 직렬 실행 스레드로 병렬 사이.  

         B. 대기 스레드 두 가지 경우로 분할되고, 하나의 제한 대기이며, 나머지는 무한정 대기한다.

         C. 제한 대기 :이 상태에서 스레드를 CPU의 실행 시간을 할당 할 수 없습니다 것입니다, 당신은 다음 실행 상태가 명시 적으로 재개 다른 스레드를 기다릴 필요가있다.

            가. 전화 Thread.join()방법. 우리는 실행 스레드의 끝에 기다린 다음 스레드에 일어나해야합니다.

            B. 호출 Object.wait()방법. (가) 통지 ()의 notifyAll ()가 깨어 나면 사용하여 다른 스레드 때까지 기다려야 할 것이다.

        다른 스레드가 명시 적으로 일 재개, 또한 일정 시간 후 시스템에 의해 자동으로 일어나, 다음 실행 상태를 입력 할 수 있습니다,이 상태에서 스레드를 CPU의 실행 시간을 할당되지 않습니다 : D. 무한정 기다립니다.

           가. 전화 Thread.sleep(timeout)방법. 이 방법은 보류 객체 잠금을 해제하지 않습니다.

           B. 호출 Object.wait(timeout)방법. 이 방법은 보유하는 잠금을 해제합니다.

           C는. 부르는 Thread.join(timeout)방법을.

(4) 쓰레드를 종료 : 스레드 때 run()실행에있어서, 상기 나사 단부의 끝.

도시 된 바와 같이 전체 스레드 상태 :

 

실험 요약의 두 번째 부분

실험 1 :  의 도입 (13 개) 모자 샘플 프로그램, 시험 절차 및 코드 주석.

시험 절차 (1)

에서 elipse IDE의 교과서를 스타트 업 (585) 의 페이지 사이즈 13-1 이해 프로그램을 실행 한 결과와 관련하여;

생성 된 다른 디렉토리에 JAR 파일을 추가, 아카이브가 실행되고, 프로그램은 자원을 확인하고, 현재 디렉토리에서 JAR 파일에서 읽을 수 없습니다.

만들 수 JAR의 방법 파일을;

ResourceTest

 

자원을 패키지;
java.awt의를 가져옵니다. *;
수입는 java.io *;
java.net을 가져옵니다. *;
java.util의를 가져옵니다. *;
javax.swing의 수입. *;
/ **
 * @version 2015년 6월 12일 1.41
 * @author 케이 HORSTMANN
 * /
공용 클래스 ResourceTest
{
   공공 정적 무효 메인 (문자열 []에 args)
   {
      EventQueue.invokeLater (() -> {
         JFrame의 프레임 = 새로운 ResourceTestFrame () ;
         frame.setTitle ( "ResourceTest");
         frame.setDefaultCloseOperation (의 JFrame.EXIT_ON_CLOSE)
         frame.setVisible (TRUE); //可视化
      });
   }
}
/ **
 *로드 이미지와 텍스트 자원하는 프레임.
 * /
클래스 ResourceTestFrame가 JFrame의 확장
{
   개인 정적 최종 INT의 DEFAULT_WIDTH = 300;
   개인 정적 최종 INT의 DEFAULT_HEIGHT = 300;
   ResourceTestFrame 공개 ()
   {
      에는 setSize (DEFAULT_WIDTH, DEFAULT_HEIGHT)
      aboutURL = getClass (의 URL) ( "about.gif")의 getResource이 ;. // 소스 코드, 대상 파일을 결정로드
      이미지 IMG를 = 새로운 이미지 아이콘 (aboutURL) .getImage (); // 아이콘 설정
      setIconImage (IMG);
      JTextArea에 텍스트 영역을 새로운 JTextArea에 () =;
      스트림의 InputStream = ( "ABOUT.TXT") getClass () 같이 getResourceAsStream.; //读取文件
      시도 (스캐너 = 새로운 스캐너 (스트림 "UTF-8"))
      {
         동안 (in.hasNext ())
            textArea.append (in.nextLine () + "\ n");
      }
      (텍스트 영역)을 추가; //添加到文件区域
   }
}

 

  실험은 출력 화면을 결과 :

 

 

 

 자세한 과정은 다음과 같습니다

                     (결과는 다시 이전과 열)

 

 시험 절차 2 :

에서 elipse IDE Debuging 을 ThreadTest 프로그램의 조합 결과를 알 수있는 프로그램;

L은  스레드의 개념을 이해;

리터  에 의해 마스터 확장 클래스 스레드의 스레드를 구현하는 방법;

리터의  사용 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

 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键可以多次点击。同时引入多个小球同时运动且相互不影响。以至出现上图中我们在视觉上可以观察到的小球线性的运动轨迹。通过对比这也正是体现了线程的优点——提高系统资源利用率,改善系统性能。

第三部分  实验总结

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

 

 

추천

출처www.cnblogs.com/wf-001128/p/12045785.html