201771010124 王海珍 《面向对象设计 Java》第十六周实验总结

实验十六  线程技术

实验时间 2017-12-8

1、实验目的与要求

(1) 掌握线程概念;

(2) 掌握线程创建的两种技术;

(3) 理解和掌握线程的优先级属性及调度方法;

(4) 掌握线程同步的概念及实现技术;

2、实验内容和步骤

实验1:测试程序并进行代码注释。

测试程序1:

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

l 掌握线程概念;

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

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

     }

}

 

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

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 M 
{

     public static void main(String[] args)
     {   
         Runnable r=new Lefthand();
         Runnable r1=new Righthand();
         Thread t=new Thread(r);
         Thread t1=new Thread(r1);
         t.start();
         t1.start();


     }
}

 测试结果如下所示

测试程序2

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

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

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

package bounce;

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

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)
      {
         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.*;

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

   /**
          * 将按钮添加到容器中
          *按钮标题
          * 按钮的动作监听器
   */
   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());
            comp.paint(comp.getGraphics());
            Thread.sleep(DELAY);
         }
      }
      catch (InterruptedException e)
      {
      }
   }
}

 

package bounce;

import java.awt.geom.*;

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

   /**
        * 获取球在当前位置的形状。
    */
   public Ellipse2D getShape()
   {
      return new Ellipse2D.Double(x, y, XSIZE, YSIZE);
   }
}

 测试结果如下所示

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

package bounceThread;

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

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);
      JPanel buttonPanel = new JPanel();
      addButton(buttonPanel, "Start", event -> addBall());
      addButton(buttonPanel, "Close", event -> System.exit(0));
      add(buttonPanel, BorderLayout.SOUTH);
      pack();
   }


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

 测试结果如下所示

测试程序3:分析以下程序运行结果并理解程序。

class Race extends Thread {

  public static void main(String args[]) {

    Race[] runner=new Race[4];

    for(int i=0;i<4;i++) runner[i]=new Race( );

   for(int i=0;i<4;i++) runner[i].start( );

   runner[1].setPriority(MIN_PRIORITY);

   runner[3].setPriority(MAX_PRIORITY);}

  public void run( ) {

      for(int i=0; i<1000000; i++);

      System.out.println(getName()+"线程的优先级是"+getPriority()+"已计算完毕!");

    }

}

测试结果如下所示

测试程序4

l 教材642页程序模拟一个有若干账户的银行,随机地生成在这些账户之间转移钱款的交易。每一个账户有一个线程。在每一笔交易中,会从线程所服务的账户中随机转移一定数目的钱款到另一个随机账户。

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

package unsynch;
/**
 * 当多个线程访问一个数据结构时,这个程序显示数据损坏。
 */
public class UnsynchBankTest
{
   public static final int NACCOUNTS = 100;
   public static final double INITIAL_BALANCE = 1000;
   public static final double MAX_AMOUNT = 1000;
   public static final int DELAY = 10;
   
   public static void main(String[] args)
   {
      Bank bank = new Bank(NACCOUNTS, INITIAL_BALANCE);
      for (int i = 0; i < NACCOUNTS; i++)
      {
         int fromAccount = i;
         Runnable r = () -> {
            try
            {
               while (true)
               {
                  int toAccount = (int) (bank.size() * Math.random());
                  double amount = MAX_AMOUNT * Math.random();
                  bank.transfer(fromAccount, toAccount, amount);
                  Thread.sleep((int) (DELAY * Math.random()));
               }
            }
            catch (InterruptedException e)
            {
            }            
         };
         Thread t = new Thread(r);
         t.start();
      }
   }
}

 

package unsynch;
import java.util.*;
public class Bank
{
   private final double[] accounts;

   /**
    * @参数n表示账户数量
    * @每个帐户的初始余额
    */
   public Bank(int n, double initialBalance)
   {
      accounts = new double[n];
      Arrays.fill(accounts, initialBalance);
   }

   /**
       *  把钱从一个账户转到另一个账户。
    * @从帐户中调出参数
    * @向要转账的账户输入参数
    * @要转帐的金额
    */
   public void transfer(int from, int to, double amount)
   {
      if (accounts[from] < amount) return;
      System.out.print(Thread.currentThread());
      accounts[from] -= amount;
      System.out.printf(" %10.2f from %d to %d", amount, from, to);
      accounts[to] += amount;
      System.out.printf(" Total Balance: %10.2f%n", getTotalBalance());
   }

   /**
           * 获取所有帐户余额的总和。
           * 返回总余额
    */
   public double getTotalBalance()
   {
      double sum = 0;

      for (double a : accounts)
         sum += a;

      return sum;
   }

   /**
           *获取银行中的帐户编号.
          *  返回账号
    */
   public int size()
   {
      return accounts.length;
   }
}

 测试结果如下所示

综合编程练习

编程练习1

  1. 设计一个用户信息采集程序,要求如下:

(1) 用户信息输入界面如下图所示:

 

(2) 用户点击提交按钮时,用户输入信息显示控制台界面;

(3) 用户点击重置按钮后,清空用户已输入信息;

(4) 点击窗口关闭,程序退出。

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
import javax.swing.*;

public class Guiwork 
{
   public static void main(String[] args)
   {
      EventQueue.invokeLater(() -> {
         JFrame frame = new FrameTest();
         frame.setTitle("produce by 王海珍");
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         frame.setVisible(true);
      });
   }
}



class FrameTest extends JFrame
{
    
    private JPanel panel;
    private JTextArea text,text2;
    private JRadioButton JRadioButton1,JRadioButton2;
    private ButtonGroup ButtonGroup;
    private JLabel JLabel;
    private JCheckBox h1,h2,h3;
    private JComboBox<String> JComboBox;
    private JButton Button,Button2;
    
    
   public FrameTest()
   {
      setSize(700,500);
      panel=new JPanel();
      panel.setLayout(null);

      ButtonGroup=new ButtonGroup();
      JRadioButton1=new JRadioButton("Male",false);   JRadioButton1.setBounds(150,330, 80, 50);
      JRadioButton2=new JRadioButton("Female",false); JRadioButton2.setBounds(150,300, 80,50);
      ButtonGroup.add(JRadioButton1);
      ButtonGroup.add(JRadioButton2);
      
      addJLabel("sex:",100,300);
      addJLabel("name:",100,50);
      addJLabel("address:",100,150);
      addJLabel("Qualification:",400,50);
      addJLabel("Hobby:",400,150);
      
      
      text=new JTextArea(1,1);text.setBounds(150,70, 120, 30);text.setLineWrap(true);
      text2=new JTextArea(5,3);text2.setBounds(150,160, 130, 100);text2.setLineWrap(true);
      
      
      h1=new JCheckBox("Reading");h1.setBounds(450,160,100,30);
      h2=new JCheckBox("dancing");h2.setBounds(450,180,100,30);
      h3=new JCheckBox("singing");h3.setBounds(450,200,100,30);

      
      JComboBox=new JComboBox<>();
      JComboBox.addItem("Graduate");
      JComboBox.addItem("Graduate1");
      JComboBox.addItem("Graduate2");
      JComboBox.setBounds(500,65, 100, 20);
      
      Button = new JButton("提交");Button.setBounds(200, 400, 100, 35);
      Button2 = new JButton("重置");Button2.setBounds(400, 400, 100, 35);

      Button.addActionListener(new Action1());
      Button2.addActionListener(new Action2());
      
      panel.add(h1);
      panel.add(h2);
      panel.add(h3);
      panel.add(Button);
      panel.add(Button2);
      panel.add(JComboBox);
      panel.add(text);
      panel.add(text2);
      panel.add(JRadioButton1);
      panel.add(JRadioButton2);
      add(panel);
      
      
   }
   
   
   public void addJLabel(String n,int a,int b)
   {
       JLabel = new JLabel(n);
       JLabel.setBounds(a,b,100,50);
       panel.add(JLabel);
   }
   
   private class Action1 implements ActionListener
   {
   public void actionPerformed(ActionEvent event)
       {        
       System.out.println("name:"+text.getText()+"\n"+"address:"+text2.getText());
       System.out.println("Qualification:"+JComboBox.getSelectedItem());
       System.out.println("Hobby:");
       if(h1.isSelected()==true)System.out.print(h1.getText());
       if(h2.isSelected()==true)System.out.print(h2.getText());
       if(h3.isSelected()==true)System.out.print(h3.getText());
       System.out.println("\n"+"sex:");
       if(JRadioButton1.isSelected()==true)System.out.println(JRadioButton1.getText());
       if(JRadioButton2.isSelected()==true)System.out.println(JRadioButton2.getText());
       System.out.println("\n");
       }
   } 
   private class Action2 implements ActionListener
   {
   public void actionPerformed(ActionEvent event)
       {        
       text.setText(null);
       text2.setText(null);
       h1.setSelected(false);
       h2.setSelected(false);
       h3.setSelected(false);
       ButtonGroup.clearSelection();
       JComboBox.setSelectedIndex(0);
       }
   }   
}

 

2.创建两个线程,每个线程按顺序输出5次“你好”,每个“你好”要标明来自哪个线程及其顺序号。

class Lefthand extends Thread {
    public void run() {
        for (int i = 1; i <= 5; i++) {
            System.out.println(i+":1.你好!");
            try {
                sleep(300);
            } catch (InterruptedException e) {
                System.out.println("Lefthand error.");
            }
        }
    }
}

class Righthand extends Thread {
    public void run() {
        for (int i = 1; i <= 5; i++) {
            System.out.println(i+":2.你好!");
            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();
    }
}

 结果如下所示

第三部分  实验总结

         本周实验的主要学习内容是关于线程的了解,关于什么是线程,线程安全的集合,中断线程,线程的状态等几个方面进行了学习。而通过本次实验感觉自己也有了一定的进步,当然了在做本次实验的时候也有参考其他同学的优秀的作业成果的。

 

posted on 2018-12-16 10:40  颜值担当  阅读(209)  评论(0编辑  收藏  举报