一:理论部分

1.程序:是一段静态的代码,它是应用程序执行的蓝本。

2.进程:是程序的一次动态执行,它对应了从代码加载、执行至执行完毕的一个完整过程。

3.多线程:是进程执行过程中产生的多条执行线索。线程是比进程执行更小的单位。

4.线程不能独立存在,必须存在于进程中,同一进程的各线程间共享进程空间的数据。

5.Java实现多线程有两种途径:

‐创建Thread类的子类
‐在程序中定义实现Runnable接口的类

6.用Thread类的子类创建线程:

a.首先需从Thread类派生出一个子类,在该子类中重写run()方法。

b.然后用创建该子类的对象

c.最后用start()方法启动线程

7.用Runnable()接口实现线程

a.首先设计一个实现Runnable接口的类;

b.然后在类中根据需要重写run方法;

c.再创建该类对象,以此对象为参数建立Thread类的对象;

d.调用Thread类对象的start方法启动线程,将CPU执行权转交到run方法

8.线程的终止:

a.首先设计一个实现Runnable接口的类;
b.然后在类中根据需要重写run方法;
c.再创建该类对象,以此对象为参数建立Thread类的对象;
d.调用Thread类对象的start方法启动线程,将CPU执行权转交到run方法

void interrupt()
e.向一个线程发送一个中断请求,同时把这个线程的“interrupted”状态置为true。
f.若该线程处于 blocked 状 态 , 会抛出InterruptedException。
9.测试线程是否被中断的方法

a.static boolean interrupted()
检测当前线程是否已被中断 , 并重置状态“interrupted”值为false。
b.boolean isInterrupted()
– 检测当前线程是否已被中断 , 不改变状态“interrupted”值.

10.线程有如下7种状态:
1)New (新建)
2) Runnable (可运行)
3) Running(运行)
4) Blocked (被阻塞)
5) Waiting (等待)
6) Timed waiting (计时等待)
7) Terminated (被终止)

11.新建线程:new(新建)线程对象刚刚创建,还没有启动,此时线程还处于不可运行状态。
例如:Thread thread=new Thread(r);
此时线程thread处于新建状态,有了相应的内存空间以及其它资源。

12.Thread类有三个与线程优先级有关的静态量:
a.MAX_PRIORITY:最大优先权,值为10;
b. MIN_PRIORITY:最小优先权,值为1;
c. NORM _PRIORITY:默认优先权,值为5.

二:实验部分

1、实验目的与要求

(1) 掌握线程概念;

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

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

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

2、实验内容和步骤

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

测试程序1:

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

l 掌握线程概念;

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

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

程序如下:

  1. class Lefthand extends Thread {
  2. public void run()
  3. {
  4. for(int i=;i<=;i++)
  5. { System.out.println("You are Students!");
  6. try{ sleep(); }
  7. catch(InterruptedException e)
  8. { System.out.println("Lefthand error.");}
  9. }
  10. }
  11. }
  12. class Righthand extends Thread {
  13. public void run()
  14. {
  15. for(int i=;i<=;i++)
  16. { System.out.println("I am a Teacher!");
  17. try{ sleep(); }
  18. catch(InterruptedException e)
  19. { System.out.println("Righthand error.");}
  20. }
  21. }
  22. }
  23. public class ThreadTest
  24. {
  25. static Lefthand left;
  26. static Righthand right;
  27. public static void main(String[] args)
  28. { left=new Lefthand();
  29. right=new Righthand();
  30. left.start();
  31. right.start();
  32. }
  33. }

使用Runable接口改造后的程序如下:

  1. class Lefthand implements Runnable {
  2. public void run()
  3. {
  4. for(int i=;i<=;i++)
  5. { System.out.println("You are Students!");
  6. try{ Thread.sleep();//休眠500毫秒
  7. }
  8. catch(InterruptedException e)
  9. { System.out.println("Lefthand error.");}
  10. }
  11. }
  12.  
  13. }
  14. class Righthand implements Runnable {
  15. public void run()
  16. {
  17. for(int i=;i<=;i++)
  18. { System.out.println("I am a Teacher!");
  19. try{ Thread.sleep();//休眠300毫秒
  20. }
  21. catch(InterruptedException e)
  22. { System.out.println("Righthand error.");}
  23. }
  24. }
  25.  
  26. }
  27. public class ThreadTest
  28. {
  29. public static void main(String[] args)
  30. {
  31.  
  32. Righthand righthand = new Righthand();//新建一个righthand对象
  33. Lefthand lefthand = new Lefthand();//新建一个lefthand对象
  34. Thread right = new Thread(righthand);//start方法在Thread类中,新建Thread类
  35. right.start();
  36. Thread left=new Thread(lefthand);
  37. left.start();
  38. }
  39. }

程序运行结果如下:

测试程序2:

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

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

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

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

程序如下:

14-1、14-2 、14-3:

  1. import java.awt.*;
  2. import java.util.*;
  3. import javax.swing.*;
  4.  
  5. /**
  6. * The component that draws the balls.
  7. * @version 1.34 2012-01-26
  8. * @author Cay Horstmann
  9. */
  10. public class BallComponent extends JPanel
  11. {
  12. private static final int DEFAULT_WIDTH = ;
  13. private static final int DEFAULT_HEIGHT = ;
  14.  
  15. private java.util.List<Ball> balls = new ArrayList<>();
  16.  
  17. /**
  18. * Add a ball to the component.
  19. * @param b the ball to add
  20. */
  21. public void add(Ball b)
  22. {
  23. balls.add(b);
  24. }
  25.  
  26. public void paintComponent(Graphics g)
  27. {
  28. super.paintComponent(g); // 擦除背景
  29. Graphics2D g2 = (Graphics2D) g;
  30. for (Ball b : balls)
  31. {
  32. g2.fill(b.getShape());
  33. }
  34. }
  35.  
  36. public Dimension getPreferredSize()
  37. {
  38. return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT); }
  39. }
  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import javax.swing.*;
  4.  
  5. /**
  6. * Shows an animated bouncing ball.
  7. * @version 1.34 2015-06-21
  8. * @author Cay Horstmann
  9. */
  10. public class Bounce
  11. {
  12. public static void main(String[] args)
  13. {
  14. EventQueue.invokeLater(() -> {
  15. JFrame frame = new BounceFrame();
  16. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  17. frame.setVisible(true);
  18. });
  19. }
  20. }
  21.  
  22. /**
  23. * The frame with ball component and buttons.
  24. */
  25. class BounceFrame extends JFrame
  26. {
  27. private BallComponent comp;
  28. public static final int STEPS = ;
  29. public static final int DELAY = ;
  30.  
  31. /**
  32. * Constructs the frame with the component for showing the bouncing ball and
  33. * Start and Close buttons
  34. */
  35. public BounceFrame()
  36. {
  37. setTitle("Bounce");
  38. comp = new BallComponent();
  39. add(comp, BorderLayout.CENTER);//使用边框布局管理器使其显示在窗口中心位置
  40. JPanel buttonPanel = new JPanel();
  41. addButton(buttonPanel, "Start", event -> addBall());//在窗口添加两个按钮
  42. addButton(buttonPanel, "Close", event -> System.exit());
  43. add(buttonPanel, BorderLayout.SOUTH);//使用边框布局管理器使其显示在窗口下方位置
  44. pack();
  45. }
  46.  
  47. /**
  48. * Adds a button to a container.
  49. * @param c the container
  50. * @param title the button title
  51. * @param listener the action listener for the button
  52. */
  53. public void addButton(Container c, String title, ActionListener listener)
  54. {
  55. JButton button = new JButton(title);
  56. c.add(button);
  57. button.addActionListener(listener);
  58. }
  59.  
  60. /**
  61. * Adds a bouncing ball to the panel and makes it bounce 1,000 times.
  62. */
  63. public void addBall()
  64. {
  65. try
  66. {
  67. Ball ball = new Ball();
  68. comp.add(ball);
  69.  
  70. for (int i = ; i <= STEPS; i++)
  71. {
  72. ball.move(comp.getBounds());
  73. comp.paint(comp.getGraphics());
  74. Thread.sleep(DELAY);
  75. }
  76. }
  77. catch (InterruptedException e)
  78. {
  79. }
  80. }
  81. }
  1. import java.awt.geom.*;
  2.  
  3. /**
  4. * A ball that moves and bounces off the edges of a rectangle
  5. * @version 1.33 2007-05-17
  6. * @author Cay Horstmann
  7. */
  8. public class Ball
  9. {
  10. private static final int XSIZE = ;
  11. private static final int YSIZE = ;
  12. private double x = ;
  13. private double y = ;
  14. private double dx = ;
  15. private double dy = ;
  16.  
  17. /**
  18. * 将球移动到下一个位置,如果球碰到其中一条边,则反向移动
  19. */
  20. public void move(Rectangle2D bounds)
  21. {
  22. x += dx;
  23. y += dy;
  24. if (x < bounds.getMinX())
  25. {
  26. x = bounds.getMinX();
  27. dx = -dx;
  28. }
  29. if (x + XSIZE >= bounds.getMaxX())
  30. {
  31. x = bounds.getMaxX() - XSIZE;
  32. dx = -dx;
  33. }
  34. if (y < bounds.getMinY())
  35. {
  36. y = bounds.getMinY();
  37. dy = -dy;
  38. }
  39. if (y + YSIZE >= bounds.getMaxY())
  40. {
  41. y = bounds.getMaxY() - YSIZE;
  42. dy = -dy;
  43. }
  44. }
  45.  
  46. /**
  47. *获取球在当前位置的形状。
  48. */
  49. public Ellipse2D getShape()
  50. {
  51. return new Ellipse2D.Double(x, y, XSIZE, YSIZE);
  52. }
  53. }

运行结果如下:

14-4:

  1. package bounceThread;
  2.  
  3. import java.awt.*;
  4. import java.awt.event.*;
  5.  
  6. import javax.swing.*;
  7.  
  8. /**
  9. * Shows animated bouncing balls.
  10. * @version 1.34 2015-06-21
  11. * @author Cay Horstmann
  12. */
  13. public class BounceThread
  14. {
  15. public static void main(String[] args)
  16. {
  17. EventQueue.invokeLater(() -> {
  18. JFrame frame = new BounceFrame();
  19. frame.setTitle("BounceThread");
  20. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  21. frame.setVisible(true);
  22. });
  23. }
  24. }
  25.  
  26. /**
  27. * The frame with panel and buttons.
  28. */
  29. class BounceFrame extends JFrame
  30. {
  31. private BallComponent comp;
  32. public static final int STEPS = ;
  33. public static final int DELAY = ;
  34.  
  35. /**
  36. * Constructs the frame with the component for showing the bouncing ball and
  37. * Start and Close buttons
  38. */
  39. public BounceFrame()
  40. {
  41. comp = new BallComponent();
  42. add(comp, BorderLayout.CENTER);//使用边框布局管理器将它放在窗口的中心位置
  43. JPanel buttonPanel = new JPanel();
  44. addButton(buttonPanel, "Start", event -> addBall());
  45. addButton(buttonPanel, "Close", event -> System.exit());
  46. add(buttonPanel, BorderLayout.SOUTH);//使用边框布局管理器将它放在窗口的中心位置
  47. pack();
  48. }
  49.  
  50. /**
  51. * Adds a button to a container.
  52. * @param c the container
  53. * @param title the button title
  54. * @param listener the action listener for the button
  55. */
  56. public void addButton(Container c, String title, ActionListener listener)
  57. {
  58. JButton button = new JButton(title);
  59. c.add(button);
  60. button.addActionListener(listener);
  61. }
  62.  
  63. /**
  64. * Adds a bouncing ball to the canvas and starts a thread to make it bounce
  65. */
  66. public void addBall()
  67. {
  68. Ball ball = new Ball();
  69. comp.add(ball);
  70. Runnable r = () -> {
  71. try
  72. {
  73. for (int i = ; i <= STEPS; i++)
  74. {
  75. ball.move(comp.getBounds());
  76. comp.repaint();
  77. Thread.sleep(DELAY);
  78. }
  79. }
  80. catch (InterruptedException e)
  81. {
  82. }
  83. };
  84. Thread t = new Thread(r);
  85. t.start();//调用Thread类中的start方法
  86. }
  87. }
  1. package bounceThread;
  2.  
  3. import java.awt.*;
  4. import java.util.*;
  5. import javax.swing.*;
  6.  
  7. /**
  8. * The component that draws the balls.
  9. * @version 1.34 2012-01-26
  10. * @author Cay Horstmann
  11. */
  12. public class BallComponent extends JComponent
  13. {
  14. private static final int DEFAULT_WIDTH = ;
  15. private static final int DEFAULT_HEIGHT = ;
  16.  
  17. private java.util.List<Ball> balls = new ArrayList<>();
  18.  
  19. /**
  20. * Add a ball to the panel.
  21. * @param b the ball to add
  22. */
  23. public void add(Ball b)
  24. {
  25. balls.add(b);
  26. }
  27.  
  28. public void paintComponent(Graphics g)
  29. {
  30. Graphics2D g2 = (Graphics2D) g;
  31. for (Ball b : balls)
  32. {
  33. g2.fill(b.getShape());
  34. }
  35. }
  36.  
  37. public Dimension getPreferredSize() { return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT); }
  38. }
  1. package bounceThread;
  2.  
  3. import java.awt.geom.*;
  4.  
  5. /**
  6. A ball that moves and bounces off the edges of a
  7. rectangle
  8. * @version 1.33 2007-05-17
  9. * @author Cay Horstmann
  10. */
  11. public class Ball
  12. {
  13. private static final int XSIZE = ;
  14. private static final int YSIZE = ;
  15. private double x = ;
  16. private double y = ;
  17. private double dx = ;
  18. private double dy = ;
  19.  
  20. /**
  21. Moves the ball to the next position, reversing direction
  22. if it hits one of the edges
  23. */
  24. public void move(Rectangle2D bounds)
  25. {
  26. x += dx;
  27. y += dy;
  28. if (x < bounds.getMinX())
  29. {
  30. x = bounds.getMinX();
  31. dx = -dx;
  32. }
  33. if (x + XSIZE >= bounds.getMaxX())
  34. {
  35. x = bounds.getMaxX() - XSIZE;
  36. dx = -dx;
  37. }
  38. if (y < bounds.getMinY())
  39. {
  40. y = bounds.getMinY();
  41. dy = -dy;
  42. }
  43. if (y + YSIZE >= bounds.getMaxY())
  44. {
  45. y = bounds.getMaxY() - YSIZE;
  46. dy = -dy;
  47. }
  48. }
  49.  
  50. /**
  51. Gets the shape of the ball at its current position.
  52. */
  53. public Ellipse2D getShape()
  54. {
  55. return new Ellipse2D.Double(x, y, XSIZE, YSIZE);
  56. }
  57. }
  1.  

程序运行结果如下:

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

  1. class Race extends Thread {
  2. public static void main(String args[]) {
  3. Race[] runner=new Race[];
  4. for(int i=;i<;i++) runner[i]=new Race( );
  5. for(int i=;i<;i++) runner[i].start( );
  6. runner[].setPriority(MIN_PRIORITY);//设置1为最小优先级
  7. runner[].setPriority(MAX_PRIORITY);//设置3位最大优先级
  8. }
  9. public void run( ) {
  10. for(int i=; i<; i++);//运行时产生的延时,这段时间在执行for循环(为空时也执行),直到执行结束后开始执行后面的语句(也可用sleep抛出异常)
  11. System.out.println(getName()+"线程的优先级是"+getPriority()+"已计算完毕!");
  12. }
  13. }

程序运行结果如下:

测试程序4

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

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

  1. package unsynch;
  2.  
  3. /**
  4. * This program shows data corruption when multiple threads access a data structure.
  5. * @version 1.31 2015-06-21
  6. * @author Cay Horstmann
  7. */
  8. public class UnsynchBankTest
  9. {
  10. public static final int NACCOUNTS = ;
  11. public static final double INITIAL_BALANCE = ;//期初余额
  12. public static final double MAX_AMOUNT = ;//最大数量
  13. public static final int DELAY = ;//延时
  14.  
  15. public static void main(String[] args)
  16. {
  17. Bank bank = new Bank(NACCOUNTS, INITIAL_BALANCE);
  18. for (int i = ; i < NACCOUNTS; i++)
  19. {
  20. int fromAccount = i;
  21. Runnable r = () -> {
  22. try
  23. {
  24. while (true)
  25. {
  26. int toAccount = (int) (bank.size() * Math.random());//生成随机数
  27. double amount = MAX_AMOUNT * Math.random();
  28. bank.transfer(fromAccount, toAccount, amount);
  29. Thread.sleep((int) (DELAY * Math.random()));
  30. }
  31. }
  32. catch (InterruptedException e)
  33. {
  34. }
  35. };
  36. Thread t = new Thread(r);
  37. t.start();
  38. }
  39. }
  40. }
  1. package unsynch;
  2.  
  3. import java.util.*;
  4.  
  5. /**
  6. * A bank with a number of bank accounts.
  7. * @version 1.30 2004-08-01
  8. * @author Cay Horstmann
  9. */
  10. public class Bank
  11. {
  12. private final double[] accounts;
  13.  
  14. /**
  15. * Constructs the bank.
  16. * @param n the number of accounts
  17. * @param initialBalance the initial balance for each account
  18. */
  19. public Bank(int n, double initialBalance)
  20. {
  21. accounts = new double[n];
  22. Arrays.fill(accounts, initialBalance);
  23. }
  24.  
  25. /**
  26. * Transfers money from one account to another.
  27. * @param from the account to transfer from
  28. * @param to the account to transfer to
  29. * @param amount the amount to transfer
  30. */
  31. public void transfer(int from, int to, double amount)
  32. {
  33. if (accounts[from] < amount) return;
  34. System.out.print(Thread.currentThread());
  35. accounts[from] -= amount;
  36. System.out.printf(" %10.2f from %d to %d", amount, from, to);
  37. accounts[to] += amount;
  38. System.out.printf(" Total Balance: %10.2f%n", getTotalBalance());
  39. }
  40.  
  41. /**
  42. * Gets the sum of all account balances.
  43. * @return the total balance
  44. */
  45. public double getTotalBalance()
  46. {
  47. double sum = ;
  48.  
  49. for (double a : accounts)
  50. sum += a;
  51.  
  52. return sum;
  53. }
  54.  
  55. /**
  56. * Gets the number of accounts in the bank.
  57. * @return the number of accounts
  58. */
  59. public int size()
  60. {
  61. return accounts.length;
  62. }
  63. }
  1.  

运行结果:

综合编程练习

编程练习1

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

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

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

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

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

程序如下:

  1. import java.awt.EventQueue;
  2.  
  3. import javax.swing.JFrame;
  4.  
  5. public class Mian {
  6. public static void main(String[] args) {
  7. EventQueue.invokeLater(() -> {
  8. DemoJFrame page = new DemoJFrame();
  9. });
  10. }
  11. }
  1. import java.awt.Color;
  2. import java.awt.Dimension;
  3. import java.awt.FlowLayout;
  4. import java.awt.GridLayout;
  5. import java.awt.LayoutManager;
  6. import java.awt.Panel;
  7. import java.awt.event.ActionEvent;
  8. import java.awt.event.ActionListener;
  9. import java.io.BufferedReader;
  10. import java.io.File;
  11. import java.io.FileInputStream;
  12. import java.io.IOException;
  13. import java.io.InputStreamReader;
  14. import java.util.ArrayList;
  15. import java.util.Timer;
  16. import java.util.TimerTask;
  17.  
  18. import javax.swing.BorderFactory;
  19. import javax.swing.ButtonGroup;
  20. import javax.swing.ButtonModel;
  21. import javax.swing.JButton;
  22. import javax.swing.JCheckBox;
  23. import javax.swing.JComboBox;
  24. import javax.swing.JFrame;
  25. import javax.swing.JLabel;
  26. import javax.swing.JPanel;
  27. import javax.swing.JRadioButton;
  28. import javax.swing.JTextField;
  29.  
  30. public class DemoJFrame extends JFrame {
  31. private JPanel jPanel1;
  32. private JPanel jPanel2;
  33. private JPanel jPanel3;
  34. private JPanel jPanel4;
  35. private JTextField fieldname;
  36. private JComboBox comboBox;
  37. private JTextField fieldadress;
  38. private ButtonGroup bg;
  39. private JRadioButton nan;
  40. private JRadioButton nv;
  41. private JCheckBox sing;
  42. private JCheckBox dance;
  43. private JCheckBox draw;
  44.  
  45. public DemoJFrame() {
  46. // 设置窗口大小
  47. this.setSize(, );
  48. // 设置可见性
  49. this.setVisible(true);
  50. // 设置标题
  51. this.setTitle("Student Detail");
  52. // 设置关闭操作
  53. this.setDefaultCloseOperation(EXIT_ON_CLOSE);
  54. // 设置窗口居中
  55. WinCenter.center(this);
  56. // 创建四个面板对象
  57. jPanel1 = new JPanel();
  58. setJPanel1(jPanel1);
  59. jPanel2 = new JPanel();
  60. setJPanel2(jPanel2);
  61. jPanel3 = new JPanel();
  62. setJPanel3(jPanel3);
  63. jPanel4 = new JPanel();
  64. setJPanel4(jPanel4);
  65. // 设置容器为流式布局
  66. FlowLayout flowLayout = new FlowLayout();
  67. this.setLayout(flowLayout);
  68. // 将四个面板添加到容器中
  69. this.add(jPanel1);
  70. this.add(jPanel2);
  71. this.add(jPanel3);
  72. this.add(jPanel4);
  73.  
  74. }
  75.  
  76. /*
  77. * 设置面板一
  78. */
  79. private void setJPanel1(JPanel jPanel) {
  80. jPanel.setPreferredSize(new Dimension(, ));//设置此组件的首选大小
  81. // 给面板的布局设置为网格布局 一行4列
  82. jPanel.setLayout(new GridLayout(, ));
  83. JLabel name = new JLabel("Name:");
  84. name.setSize(, );
  85. fieldname = new JTextField("");
  86. fieldname.setSize(, );
  87. JLabel study = new JLabel("Qualification:");
  88. comboBox = new JComboBox();
  89. comboBox.addItem("Graduate");
  90. comboBox.addItem("senior");
  91. comboBox.addItem("Undergraduate");
  92. jPanel.add(name);
  93. jPanel.add(fieldname);
  94. jPanel.add(study);
  95. jPanel.add(comboBox);
  96.  
  97. }
  98.  
  99. /*
  100. * 设置面板二
  101. */
  102. private void setJPanel2(JPanel jPanel) {
  103. jPanel.setPreferredSize(new Dimension(, ));
  104. // 给面板的布局设置为网格布局 一行4列
  105. jPanel.setLayout(new GridLayout(, ));
  106. JLabel name = new JLabel("Address:");
  107. fieldadress = new JTextField();
  108. fieldadress.setPreferredSize(new Dimension(, ));
  109. JLabel study = new JLabel("Hobby:");
  110. JPanel selectBox = new JPanel();
  111. selectBox.setBorder(BorderFactory.createTitledBorder(""));
  112. selectBox.setLayout(new GridLayout(, ));
  113. sing = new JCheckBox("Singing");
  114. dance = new JCheckBox("Dancing");
  115. draw = new JCheckBox("Reading");
  116. selectBox.add(sing);
  117. selectBox.add(dance);
  118. selectBox.add(draw);
  119. jPanel.add(name);
  120. jPanel.add(fieldadress);
  121. jPanel.add(study);
  122. jPanel.add(selectBox);
  123. }
  124.  
  125. /*
  126. * 设置面板三
  127. */
  128. private void setJPanel3(JPanel jPanel) {
  129. jPanel.setPreferredSize(new Dimension(, ));
  130. FlowLayout flowLayout = new FlowLayout(FlowLayout.LEFT);
  131. jPanel.setLayout(flowLayout);
  132. JLabel sex = new JLabel("Sex:");
  133. JPanel selectBox = new JPanel();
  134. selectBox.setBorder(BorderFactory.createTitledBorder(""));
  135. selectBox.setLayout(new GridLayout(, ));
  136. bg = new ButtonGroup();
  137. nan = new JRadioButton("Male");
  138. nv = new JRadioButton("Female");
  139. bg.add(nan);
  140. bg.add(nv);
  141. selectBox.add(nan);
  142. selectBox.add(nv);
  143. jPanel.add(sex);
  144. jPanel.add(selectBox);
  145.  
  146. }
  147.  
  148. /*
  149. * 设置面板四
  150. */
  151. private void setJPanel4(JPanel jPanel) {
  152. // TODO 自动生成的方法存根
  153. jPanel.setPreferredSize(new Dimension(, ));
  154. FlowLayout flowLayout = new FlowLayout(FlowLayout.CENTER, , );
  155. jPanel.setLayout(flowLayout);
  156. jPanel.setLayout(flowLayout);
  157. JButton sublite = new JButton("Validate");
  158. JButton reset = new JButton("Reset");
  159. sublite.addActionListener((e) -> valiData());
  160. reset.addActionListener((e) -> Reset());
  161. jPanel.add(sublite);
  162. jPanel.add(reset);
  163. }
  164.  
  165. /*
  166. * 提交数据
  167. */
  168. private void valiData() {
  169. // 拿到数据
  170. String name = fieldname.getText().toString().trim();
  171. String xueli = comboBox.getSelectedItem().toString().trim();
  172. String address = fieldadress.getText().toString().trim();
  173. System.out.println(name);
  174. System.out.println(xueli);
  175. String hobbystring="";
  176. if (sing.isSelected()) {
  177. hobbystring+="Singing ";
  178. }
  179. if (dance.isSelected()) {
  180. hobbystring+="Dancing ";
  181. }
  182. if (draw.isSelected()) {
  183. hobbystring+="Reading ";
  184. }
  185. System.out.println(address);
  186. if (nan.isSelected()) {
  187. System.out.println("Male");
  188. }
  189. if (nv.isSelected()) {
  190. System.out.println("Female");
  191. }
  192. System.out.println(hobbystring);
  193. }
  194.  
  195. /*
  196. * 重置
  197. */
  198. private void Reset() {
  199. fieldadress.setText(null);
  200. fieldname.setText(null);
  201. comboBox.setSelectedIndex();
  202. sing.setSelected(false);
  203. dance.setSelected(false);
  204. draw.setSelected(false);
  205. bg.clearSelection();
  206. }
  207. }
  1. import java.awt.Dimension;
  2. import java.awt.Toolkit;
  3. import java.awt.Window;
  4.  
  5. public class WinCenter {
  6. public static void center(Window win){
  7. Toolkit tkit = Toolkit.getDefaultToolkit();//获取默认工具包
  8. Dimension sSize = tkit.getScreenSize();//获取屏幕的大小
  9. Dimension wSize = win.getSize();
  10. if(wSize.height > sSize.height){
  11. wSize.height = sSize.height;
  12. }
  13. if(wSize.width > sSize.width){
  14. wSize.width = sSize.width;
  15. }
  16. win.setLocation((sSize.width - wSize.width)/ , (sSize.height - wSize.height)/ );//将组件移到新的位置
  17. }
  18. }

运行结果:

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

  1. package test2;
  2. class Lefthand extends Thread {
  3.  
  4. public void run()
  5.  
  6. {
  7.  
  8. for(int i=;i<=;i++)
  9.  
  10. { System.out.println("1.你好");
  11.  
  12. try{ sleep(); }
  13.  
  14. catch(InterruptedException e)
  15.  
  16. { System.out.println("Lefthand error.");}
  17.  
  18. }
  19.  
  20. }
  21.  
  22. }
  23.  
  24. class Righthand extends Thread {
  25.  
  26. public void run()
  27.  
  28. {
  29.  
  30. for(int i=;i<=;i++)
  31.  
  32. { System.out.println("2.你好");
  33.  
  34. try{ sleep(); }
  35.  
  36. catch(InterruptedException e)
  37.  
  38. { System.out.println("Righthand error.");}
  39.  
  40. }
  41.  
  42. }
  43.  
  44. }
  45.  
  46. public class AAAA
  47.  
  48. {
  49.  
  50. static Lefthand left;
  51.  
  52. static Righthand right;
  53.  
  54. public static void main(String[] args)
  55.  
  56. { left=new Lefthand();
  57.  
  58. right=new Righthand();
  59.  
  60. left.start();
  61.  
  62. right.start();
  63.  
  64. }
  65.  
  66. }

运行结果:

3. 完善实验十五 GUI综合编程练习程序。

实验一:

  1. import java.awt.*;
  2. import javax.swing.*;
  3.  
  4. public class CardTest {
  5. public static void main(String[] args) {
  6. EventQueue.invokeLater(() -> {
  7. JFrame frame = new Main();
  8. frame.setTitle("身份证");
  9. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  10. frame.setVisible(true);
  11. });
  12. }
  13. }
  1. public class Card implements Comparable<Card> {
  2. private String name;
  3. private String id;
  4. private String sex;
  5. private int age;
  6. private String area;
  7.  
  8. public String getName() {
  9. return name;
  10. }
  11.  
  12. public void setName(String name) {
  13. this.name = name;
  14. }
  15.  
  16. public String getId() {
  17. return id;
  18. }
  19.  
  20. public void setId(String id) {
  21. this.id = id;
  22. }
  23.  
  24. public String getSex() {
  25. return sex;
  26. }
  27.  
  28. public void setSex(String sex) {
  29. this.sex = sex;
  30. }
  31.  
  32. public int getAge() {
  33. return age;
  34. }
  35.  
  36. public void setAge(int age) {
  37. this.age = age;
  38. }
  39.  
  40. public String getArea() {
  41. return area;
  42. }
  43.  
  44. public void setArea(String area) {
  45. this.area = area;
  46. }
  47.  
  48. public int compareTo(Card c) {
  49. return this.name.compareTo(c.getName());
  50. }
  51.  
  52. public String toString() {
  53. return name + "\t" + id + "\t" + sex + "\t" + age + "\t" + area + "\n";
  54. }
  55. }
  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import java.io.*;
  4. import java.util.*;
  5. import javax.swing.*;
  6.  
  7. public class Main extends JFrame {
  8. private static ArrayList<Card> cardlist;
  9. private static ArrayList<Card> list;
  10. private JPanel panel;
  11. private JPanel Panel1;
  12. private static final int DEFAULT_WITH = ;
  13. private static final int DEFAULT_HEIGHT = ;
  14.  
  15. public Main() {
  16. cardlist = new ArrayList<>();
  17. Scanner scanner = new Scanner(System.in);
  18. File file = new File("E:\\身份证号.txt");
  19. try {
  20. FileInputStream fis = new FileInputStream(file);
  21. BufferedReader in = new BufferedReader(new InputStreamReader(fis));
  22. String temp = null;
  23.  
  24. while ((temp = in.readLine()) != null) {
  25. Scanner linescanner = new Scanner(temp);
  26. linescanner.useDelimiter(" ");
  27. String name = linescanner.next();
  28. String id = linescanner.next();
  29. String sex = linescanner.next();
  30. String age = linescanner.next();
  31. String area = linescanner.nextLine();
  32.  
  33. Card card = new Card();
  34. card.setName(name);
  35. card.setId(id);
  36. card.setSex(sex);
  37. int a = Integer.parseInt(age);
  38. card.setAge(a);
  39. card.setArea(area);
  40.  
  41. cardlist.add(card);
  42. }
  43.  
  44. } catch (FileNotFoundException e) {
  45. // TODO Auto-generated catch block
  46. System.out.println("信息文件找不到");
  47. e.printStackTrace();
  48. } catch (IOException e) {
  49. // TODO Auto-generated catch block
  50. System.out.println("信息文件读取错误");
  51. e.printStackTrace();
  52. }
  53. panel = new JPanel();
  54. panel.setLayout(new BorderLayout());
  55. JTextArea jt = new JTextArea();
  56. panel.add(jt);
  57. add(panel, BorderLayout.NORTH);
  58. Panel1 = new JPanel();
  59. Panel1.setLayout(new GridLayout(, ));
  60. JButton jButton = new JButton("字典排序");
  61. JButton jButton1 = new JButton("年龄最大和年龄最小");
  62. JLabel lab = new JLabel("寻找老乡:", Label.LEFT);
  63. JTextField jt1 = new JTextField();
  64. JLabel lab1 = new JLabel("寻找年龄相近的人:", Label.LEFT);
  65. JTextField jt2 = new JTextField();
  66. JLabel lab2 = new JLabel("输入你的身份证号码:", Label.LEFT);
  67. JTextField jt3 = new JTextField();
  68. JButton jButton2 = new JButton("退出");
  69.  
  70. jButton.addActionListener(new ActionListener() {
  71.  
  72. @Override
  73. public void actionPerformed(ActionEvent e) {
  74. // TODO 自动生成的方法存根
  75. Collections.sort(cardlist);
  76. jt.setText(cardlist.toString());
  77.  
  78. }
  79. });
  80.  
  81. jButton1.addActionListener(new ActionListener() {
  82.  
  83. @Override
  84. public void actionPerformed(ActionEvent e) {
  85. // TODO 自动生成的方法存根
  86. int max = , min = ;
  87. int j, k1 = , k2 = ;
  88. for (int i = ; i < cardlist.size(); i++) {
  89. j = cardlist.get(i).getAge();
  90. if (j > max) {
  91. max = j;
  92. k1 = i;
  93. }
  94. if (j < min) {
  95. min = j;
  96. k2 = i;
  97. }
  98. }
  99. jt.setText("年龄最大:" + cardlist.get(k1) + "年龄最小:" + cardlist.get(k2));
  100. }
  101. });
  102.  
  103. jButton2.addActionListener(new ActionListener() {
  104. public void actionPerformed(ActionEvent e) {
  105. dispose();
  106. System.exit();
  107. }
  108. });
  109. jt1.addActionListener(new ActionListener() {
  110. public void actionPerformed(ActionEvent e) {
  111. String find = jt1.getText();
  112. String text = "";
  113. String place = find.substring(, );
  114. for (int i = ; i < cardlist.size(); i++) {
  115. if (cardlist.get(i).getArea().substring(, ).equals(place)) {
  116. text += "\n" + cardlist.get(i);
  117. jt.setText("老乡:" + text);
  118. }
  119. }
  120. }
  121. });
  122. jt2.addActionListener(new ActionListener() {
  123. public void actionPerformed(ActionEvent e) {
  124. String yourage = jt2.getText();
  125. int a = Integer.parseInt(yourage);
  126. int near = agenear(a);
  127. jt.setText("年龄相近:" + cardlist.get(near));
  128. }
  129. });
  130. jt3.addKeyListener(new KeyAdapter() {
  131. public void keyTyped(KeyEvent e) {
  132. // TODO 自动生成的方法存根
  133. list = new ArrayList<>();
  134. Collections.sort(cardlist);
  135. String key = jt3.getText();
  136. for (int i = ; i < cardlist.size(); i++) {
  137. if (cardlist.get(i).getId().contains(key)) {
  138. list.add(cardlist.get(i));
  139. jt.setText("你可能是:\n" + list);
  140. }
  141. }
  142. }
  143. });
  144. Panel1.add(jButton);
  145. Panel1.add(jButton1);
  146. Panel1.add(lab);
  147. Panel1.add(jt1);
  148. Panel1.add(lab1);
  149. Panel1.add(jt2);
  150. Panel1.add(lab2);
  151. Panel1.add(jt3);
  152. Panel1.add(jButton2);
  153. add(Panel1, BorderLayout.SOUTH);
  154. setSize(DEFAULT_WITH, DEFAULT_HEIGHT);
  155. }
  156.  
  157. public static int agenear(int age) {
  158. int j = , min = , value = , k = ;
  159. for (int i = ; i < cardlist.size(); i++) {
  160. value = cardlist.get(i).getAge() - age;
  161. if (value < )
  162. value = -value;
  163. if (value < min) {
  164. min = value;
  165. k = i;
  166. }
  167. }
  168. return k;
  169. }
  170. }

实验二:

  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import java.io.*;
  4. import java.util.*;
  5. import javax.swing.*;
  6.  
  7. public class Demo extends JFrame {
  8. int i = , i1 = , k = , sum = ;
  9. private PrintWriter out = null;
  10. private String[] c1 = new String[];
  11. private String[] c2 = new String[];
  12.  
  13. public Demo() {
  14. JPanel panel = new JPanel();
  15. panel.setLayout(new GridLayout(, ));
  16. JTextArea jt1 = new JTextArea();
  17. JTextField jt2 = new JTextField();
  18. JTextArea jt3 = new JTextArea();
  19. panel.add(jt1);
  20. panel.add(jt2);
  21. panel.add(jt3);
  22. add(panel, BorderLayout.NORTH);
  23.  
  24. JPanel panel1 = new JPanel();
  25. panel1.setLayout(new GridLayout(, ));
  26. Button button1 = new Button("生成题目");
  27.  
  28. Button button2 = new Button("生成文件");
  29. panel1.add(button1);
  30. panel1.add(button2);
  31.  
  32. add(panel1, BorderLayout.SOUTH);
  33. setSize(, );
  34. button1.addActionListener(new ActionListener() {
  35.  
  36. @Override
  37. public void actionPerformed(ActionEvent e) {
  38. // TODO 自动生成的方法存根
  39. jt2.setText(null);
  40. jt3.setText(null);
  41. if (i < ) {
  42. int a = (int) (Math.random() * );
  43. int b = (int) (Math.random() * );
  44. int m = (int) Math.round(Math.random() * );
  45. switch (m) {
  46. case :
  47. while (b == || a % b != ) {
  48. b = (int) Math.round(Math.random() * );
  49. a = (int) Math.round(Math.random() * );
  50. }
  51. jt1.setText(i + + ": " + a + "/" + b + "=");
  52. c1[i] = jt1.getText();
  53. k = a / b;
  54. i++;
  55. break;
  56. case :
  57. jt1.setText(i + + ": " + a + "*" + b + "=");
  58. c1[i] = jt1.getText();
  59. k = a * b;
  60. i++;
  61. break;
  62. case :
  63. jt1.setText(i + + ": " + a + "+" + b + "=");
  64. c1[i] = jt1.getText();
  65. k = a + b;
  66. i++;
  67. break;
  68. case :
  69. while (a < b) {
  70. int x = a;
  71. a = b;
  72. b = x;
  73. }
  74. jt1.setText(i + + ": " + a + "-" + b + "=");
  75. c1[i] = jt1.getText();
  76. k = a - b;
  77. i++;
  78. break;
  79. }
  80. }
  81. }
  82. });
  83. jt2.addActionListener(new ActionListener() {
  84.  
  85. @Override
  86. public void actionPerformed(ActionEvent e) {
  87. // TODO 自动生成的方法存根
  88. if (i < ) {
  89. int find = Integer.parseInt(jt2.getText());
  90. String d = jt2.getText().toString().trim();
  91. if (jt2.getText() != "") {
  92. if (find == k) {
  93. sum += ;
  94. jt3.setText("答案正确");
  95. } else
  96. jt3.setText("答案错误");
  97. }
  98. c2[i1] = d;
  99. i1++;
  100. }
  101. }
  102. });
  103. button2.addActionListener(new ActionListener() {
  104.  
  105. @Override
  106. public void actionPerformed(ActionEvent e) {
  107. // TODO 自动生成的方法存根
  108. try {
  109. out = new PrintWriter("text.txt");
  110. } catch (FileNotFoundException e1) {
  111. // TODO Auto-generated catch block
  112. e1.printStackTrace();
  113. }
  114. for (int counter = ; counter < ; counter++) {
  115. out.println(c1[counter] + c2[counter]);
  116. }
  117. out.println("成绩为" + sum);
  118. out.close();
  119. }
  120. });
  121. }
  122. }
  1. import java.awt.*;
  2. import javax.swing.*;
  3.  
  4. public class DemoTest {
  5. public static void main(String[] args) {
  6. EventQueue.invokeLater(() -> {
  7. JFrame frame = new Demo();
  8. frame.setTitle("计算题");
  9. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  10. frame.setVisible(true);
  11. });
  12. }
  13. }

三:实验总结

这周主要学习了线程,线程是程序中一个单一的顺序从控制流程。在学习过程中,了解了线程创建的两种技术:用Thread类的子类创建线程以及用Runnable()接口实现线程。但是在实际操作过程中,发现自己还存在着很大的问题。在实验课上老师和学长的帮助西啊,理解了线程中的优先级。课后自己还会再继续学习。

王艳 201771010127《面向对象程序设计(java)》第十六周学习总结的更多相关文章

  1. 201571030332 扎西平措 《面向对象程序设计Java》第八周学习总结

    <面向对象程序设计Java>第八周学习总结   项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 https: ...

  2. 201771010118马昕璐《面向对象程序设计java》第八周学习总结

    第一部分:理论知识学习部分 1.接口 在Java程序设计语言中,接口不是类,而是对类的一组需求描述,由常量和一组抽象方法组成.Java为了克服单继承的缺点,Java使用了接口,一个类可以实现一个或多个 ...

  3. 201771010134杨其菊《面向对象程序设计java》第八周学习总结

    第八周学习总结 第一部分:理论知识 一.接口.lambda和内部类:  Comparator与comparable接口: 1.comparable接口的方法是compareTo,只有一个参数:comp ...

  4. 201771010134杨其菊《面向对象程序设计java》第七周学习总结

    第七周学习总结 第一部分:理论知识 1.继承是面向对象程序设计(Object Oriented Programming-OOP)中软件重用的关键技术.继承机制使用已经定义的类作为基础建立新的类定义,新 ...

  5. 201771010128 王玉兰《面象对象程序设计 (Java) 》第六周学习总结

    ---恢复内容开始--- 第一部分:基础知识总结: 1.继承 A:用已有类来构建新类的一种机制,当定义了一个新类继承一个类时,这个新类就继承了这个类的方法和域以适应新的情况: B:特点:具有层次结构. ...

  6. 201771010123汪慧和《面向对象程序设计JAVA》第六周实验总结

    一.理论部分: 1.继承 用已有类来构建新类的一种机制.当定义了一个新类继承了一个类时,这个新类就继承了这个类的方法和域,同时在新类中添加新的方法和域以适应新的情况. 2.类.超类.子类 (1)类继承 ...

  7. 201871010126 王亚涛《面向对象程序设计 JAVA》 第十三周学习总结

      内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 https://www.cnblogs.com/nwnu-daizh/p/ ...

  8. 201777010217-金云馨《面向对象程序设计Java》第八周学习总结

    项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 https://www.cnblogs.com/nwnu-daizh/p ...

  9. 201871010126 王亚涛 《面向对象程序设计 (Java)》第十七周学习总结

    内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 https://www.cnblogs.com/nwnu-daizh/p/12 ...

  10. 马凯军201771010116《面向对象程序设计Java》第八周学习总结

    一,理论知识学习部分 6.1.1 接口概念 两种含义:一,Java接口,Java语言中存在的结构,有特定的语法和结构:二,一个类所具有的方法的特征集合,是一种逻辑上的抽象.前者叫做“Java接口”,后 ...

随机推荐

  1. 15个Nodejs应用场景

    15个Nodejs应用场景 我们已经对Nodejs有了初步的了解,接下来看看Nodejs的应用场景. 2.1 Web开发:Express + EJS + Mongoose/MySQL express  ...

  2. Android 工程师眼里的大前端:GMTC 2018 参会总结

    本文由玉刚说写作平台提供写作赞助 原作者:两位低调的 Android 高手 版权声明:本文版权归微信公众号玉刚说所有,未经许可,不得以任何形式转载 概述 2018年的GMTC大会于6月22号在北京刚刚 ...

  3. IIS6服务器的请求流程(图文&源码)

    1.IIS 7开发与管理完全参考手册  http://book.51cto.com/art/200908/146040.htm 2.Web服务IIS 6   https://technet.micro ...

  4. C++类学习(2)

    Ⅰ:类概念 一:类的构成 class 类名 { public: 公有数据成员和成员函数:类的接口 protected: 保护数据成员和成员函数: private: 私有数据成员和成员函数: }://注 ...

  5. USACO 2.1 海明码 Hamming Codes (模拟+位运算+黑科技__builtin_popcount(n))

    题目描述 给出 N,B 和 D,要求找出 N 个由0或1组成的编码(1 <= N <= 64),每个编码有 B 位(1 <= B <= 8),使得两两编码之间至少有 D 个单位 ...

  6. 图论--LCA--Tarjan(离线)

    * * 给出一颗有向树,Q个查询 * 输出查询结果中每个点出现次数 * 复杂度O(n + Q); */ const int MAXN = 1010; const int MAXQ = 500010; ...

  7. Java——单双引号的区别

    单引号: 单引号包括的是单个字符,表示的是char类型.例如: char  a='1' 双引号: 双引号可以包括0个或者多个字符,表示的是String类型. 例如: String s="ab ...

  8. 假如用王者荣耀的方式学习webpack

    英雄介绍 崴博.派克诞生于遥远西方的勇士之地,拥有着高超的机械技艺,善于运用各种工具来实现一些看似不可能完成的事.游历王者大陆时机缘巧合遇到了年轻的墨子,与之成为好友.后协助大宗师墨子建造了大陆第一雄 ...

  9. 图形学_opengl纹理映射

    学了半学期的图形学,除了几个用python或是matlab比较方便的实验外,用的大多数是opengl,在这总结一下纹理贴图实验中opengl的用法. 1.编译器连接静态库 有用到glaux.h的程序, ...

  10. [Alink漫谈之三] AllReduce通信模型

    [Alink漫谈之三] AllReduce通信模型 目录 [Alink漫谈之三] AllReduce通信模型 0x00 摘要 0x01 MPI是什么 0x02 Alink 实现MPI的思想 0x03 ...