1、实验目的与要求

(1) 掌握线程概念;

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

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

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

一、理论知识

⚫ 线程的概念

(1)多线程是进程执行过程中产生的多条执行线索。

‐线程是比进程执行更小的单位。

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

‐每个线程有它自身的产生、存在和消亡的过程, 是一个动态的概念。

‐多线程意味着一个程序的多行语句可以看上去几 乎在同一时间内同时运行。

(2)Java实现多线程有两种途径: ‐创建Thread类的子类

‐在程序中定义实现Runnable接口的类

(3)用Thread类的子类创建线程:首先需从Thread类派生出一个子类,在该子类中 重写run()方法,然后用创建该子类的对象,最后用start()方法启动线程。

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

(5)线程两种创建方法比较:

实现Runnable接口的优势: 符合OO设计的思想 •便于用extends继承其它类

采用继承Thread类方法的优点:代码简单

⚫ 中断线程

(1)当线程的run方法执行方法体中最后一条语句后, 或者出现了在run方法中没有捕获的异常时,线 程将终止,让出CPU使用权。

(2)调用interrupt()方法也可终止线程。 void interrupt() – 向一个线程发送一个中断请求,同时把这个线 程的“interrupted”状态置为true。

(3)Java提供了几个用于测试线程是否被中断的方法。 ⚫ static boolean interrupted() – 检测当前线程是否已被中断 , 并重置状态 “interrupted”值为false。 ⚫ boolean isInterrupted() – 检测当前线程是否已被中断 , 不改变状态 “interrupted”值 。

⚫ 线程状态

(1)利用各线程的状态变换,可以控制各个线程轮流 使用CPU,体现多线程的并行性特征。

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

(3)其他判断和影响线程状态的方法:

➢join():等待指定线程的终止。

➢join(long millis):经过指定时间等待终止指定 的线程。

➢isAlive():测试当前线程是否在活动。

➢yield():让当前线程由“运行状态”进入到“就 绪状态” ,从而让其它具有相同优先级的等待线程 获取执行权。

⚫ 多线程调度

(1)Java提供一个线程调度器来监控程序启动后进入 可运行状态的所有线程。线程调度器按照线程的 优先级决定应调度哪些线程来执行。

(2)Java 的线程调度采用优先级策略:

➢ 优先级高的先执行,优先级低的后执行;

➢ 多线程系统会自动为每个线程分配一个优先级,缺省 时,继承其父类的优先级;

➢ 任务紧急的线程,其优先级较高;

➢ 同优先级的线程按“先进先出”的队列原则;

(3)调用setPriority(int a)重置当前线程的优先级, a 取值可以是前述的三个静态量。

调用getPriority()获得当前线程优先级。

(4)下面几种情况下,当前运行线程会放弃CPU: – 线程调用了yield() 或sleep() 方法;

– 抢先式系统下,有高优先级的线程参与调度;

– 由于当前线程进行I/O访问、外存读写、等待用 户输入等操作导致线程阻塞;或者是为等候一 个条件变量,以及线程调用wait() 方法。

⚫ 线程同步

(1)多线程并发运行不确定性问题解决方案:引入线 程同步机制,使得另一线程要使用该方法,就只 能等待

(2)在Java中解决多线程同步问题的方法有两种:

解决方案一:锁对象与条件对象

用ReentrantLock保护代码块的基本结构如下: myLock.lock();

try { critical section }

finally{ myLock.unlock(); }

(3)解决方案二: synchronized关键字

synchronized关键字作用: ➢ 某个类内方法用synchronized 修饰后,该方 法被称为同步方法;

➢ 只要某个线程正在访问同步方法,其他线程欲要访问同步方法就被阻塞,直至线程从同步方法返回前唤醒被阻塞线程,其他线程方可能进入同步方法。

(4)在同步方法中使用wait()、notify 和notifyAll()方法

一个线程在使用的同步方法中时,可能根据问题 的需要,必须使用wait()方法使本线程等待,暂 时让出CPU的使用权,并允许其它线程使用这个 同步方法。

线程如果用完同步方法,应当执行notifyAll()方 法通知所有由于使用这个同步方法而处于等待的 线程结束等待。

二、实验内容和步骤

实验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{ Thread.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{Thread.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. { Runnable left=new Lefthand();
  29. Runnable right=new Righthand();
  30. Thread t=new Thread(left);
  31. Thread s=new Thread(right);
  32. left=new Lefthand();
  33. right=new Righthand();
  34. t.start();
  35. s.start();
  36. }
  37. }

Thread

测试程序2:

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

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

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

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

(1)

  1. package bounce;
  2.  
  3. import java.awt.geom.*;
  4.  
  5. /**
  6. * A ball that moves and bounces off the edges of a rectangle
  7. * @version 1.33 2007-05-17
  8. * @author Cay Horstmann
  9. */
  10. public class Ball
  11. {//定义球的大小
  12. private static final int XSIZE = 15;
  13. private static final int YSIZE = 15;
  14. private double x = 0;
  15. private double y = 0;
  16. private double dx = 1;
  17. private double dy = 1;
  18.  
  19. /**
  20. * Moves the ball to the next position, reversing direction if it hits one of the edges
  21. */
  22. public void move(Rectangle2D bounds)
  23. { // 定义球的运行轨迹
  24. x += dx;
  25. y += dy;
  26. if (x < bounds.getMinX())
  27. {
  28. x = bounds.getMinX();
  29. dx = -dx;
  30. }
  31. if (x + XSIZE >= bounds.getMaxX())
  32. {
  33. x = bounds.getMaxX() - XSIZE;
  34. dx = -dx;
  35. }
  36. if (y < bounds.getMinY())
  37. {
  38. y = bounds.getMinY();
  39. dy = -dy;
  40. }
  41. if (y + YSIZE >= bounds.getMaxY())
  42. {
  43. y = bounds.getMaxY() - YSIZE;
  44. dy = -dy;
  45. }//四次定义移动逻辑,
  46. }
  47.  
  48. /**
  49. * Gets the shape of the ball at its current position.
  50. */
  51. public Ellipse2D getShape()
  52. {
  53. return new Ellipse2D.Double(x, y, XSIZE, YSIZE);
  54. }
  55. }

Ball

  1. package bounce;
  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 JPanel
  13. { //定义长、宽
  14. private static final int DEFAULT_WIDTH = 450;
  15. private static final int DEFAULT_HEIGHT = 350;
  16.  
  17. private java.util.List<Ball> balls = new ArrayList<>();
  18.  
  19. /**
  20. * Add a ball to the component.
  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. super.paintComponent(g); // erase background
  31. Graphics2D g2 = (Graphics2D) g;
  32. for (Ball b : balls)
  33. {
  34. g2.fill(b.getShape());
  35. }
  36. }
  37.  
  38. public Dimension getPreferredSize() { return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT); }
  39. }

BallComponent

  1. package bounce;
  2.  
  3. import java.awt.*;
  4. import java.awt.event.*;
  5. import javax.swing.*;
  6.  
  7. /**
  8. * Shows an animated bouncing ball.
  9. * @version 1.34 2015-06-21
  10. * @author Cay Horstmann
  11. */
  12. public class Bounce
  13. {
  14. public static void main(String[] args)
  15. {
  16. EventQueue.invokeLater(() -> {
  17. JFrame frame = new BounceFrame();
  18. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭界面
  19. frame.setVisible(true);//结果可见
  20. });
  21. }
  22. }
  23.  
  24. /**
  25. * The frame with ball component and buttons.
  26. */
  27. class BounceFrame extends JFrame
  28. {
  29. private BallComponent comp;
  30. public static final int STEPS = 1000;
  31. public static final int DELAY = 3;
  32.  
  33. /**
  34. * Constructs the frame with the component for showing the bouncing ball and
  35. * Start and Close buttons
  36. */
  37. public BounceFrame()
  38. {
  39. setTitle("Bounce");
  40. comp = new BallComponent();
  41. add(comp, BorderLayout.CENTER);//放到框架居中位置
  42. JPanel buttonPanel = new JPanel();
  43. addButton(buttonPanel, "Start", event -> addBall());//按钮对象添加到buttonPanel中
  44. addButton(buttonPanel, "Close", event -> System.exit(0));
  45. add(buttonPanel, BorderLayout.SOUTH);//整体放到南端
  46. pack();
  47. }
  48.  
  49. /**
  50. * Adds a button to a container.
  51. * @param c the container
  52. * @param title the button title
  53. * @param listener the action listener for the button
  54. */
  55. public void addButton(Container c, String title, ActionListener listener)
  56. {
  57. JButton button = new JButton(title);//生成title按钮
  58. c.add(button);
  59. button.addActionListener(listener);
  60. }
  61.  
  62. /**
  63. * Adds a bouncing ball to the panel and makes it bounce 1,000 times.
  64. */
  65. public void addBall()
  66. {
  67. try
  68. {
  69. Ball ball = new Ball();
  70. comp.add(ball);
  71.  
  72. for (int i = 1; i <= STEPS; i++)
  73. {
  74. ball.move(comp.getBounds());//调用move方法来显示
  75. comp.paint(comp.getGraphics());
  76. Thread.sleep(DELAY);//休眠
  77. }
  78. }
  79. //抛出异常
  80. catch (InterruptedException e)
  81. {
  82. }
  83. }
  84. }

Bounce

(2)   前两个程序如(1)所示,

  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 = 1000;
  33. public static final int DELAY = 5;
  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(0));
  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 = () -> { //实现一个BallRunnable类,将动画代码放到run方法中
  71. try
  72. {
  73. for (int i = 1; i <= STEPS; i++)
  74. {
  75. ball.move(comp.getBounds());
  76. comp.repaint();
  77. Thread.sleep(DELAY);//捕获sleep方法抛出的异常InterruptedException
  78. }
  79. }
  80. catch (InterruptedException e)
  81. {
  82. }
  83. };
  84. Thread t = new Thread(r);
  85. t.start();
  86. }
  87. }

BounceThread

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

  1. class Race extends Thread {
  2. public static void main(String args[]) {
  3. Race[] runner=new Race[4];
  4. for(int i=0;i<4;i++)
  5. runner[i]=new Race( );
  6. for(int i=0;i<4;i++)
  7. runner[i].start( );
  8. runner[1].setPriority(MIN_PRIORITY);//设置线程的最小优先级
  9. runner[3].setPriority(MAX_PRIORITY);}//设置线程的最大优先级
  10. public void run( ) {
  11. for(int i=0; i<1000000; i++);//延时作用,执行空语句
  12. System.out.println(getName()+"线程的优先级是"+getPriority()+"已计算完毕!");
  13. }
  14. }

测试程序4

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

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

bank

  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 = 100;
  11. public static final double INITIAL_BALANCE = 1000;
  12. public static final double MAX_AMOUNT = 1000;
  13. public static final int DELAY = 10;
  14.  
  15. public static void main(String[] args)
  16. {
  17. Bank bank = new Bank(NACCOUNTS, INITIAL_BALANCE);
  18. for (int i = 0; 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. }

UnsynchBankTest

综合编程练习

编程练习1

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

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

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

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

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

  1. import java.awt.EventQueue;
  2.  
  3. import javax.swing.JFrame;
  4.  
  5. public class Main {
  6. public static void main(String[] args) {
  7. EventQueue.invokeLater(() -> {
  8. DemoJFrame page = new DemoJFrame();
  9. });
  10. }
  11. }

Main

  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)/ 2, (sSize.height - wSize.height)/ 2);
  17. }
  18. }

WinCenter

  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import javax.swing.*;
  4. import javax.swing.border.*;
  5. public class DemoJFrame extends JFrame {
  6. public DemoJFrame() {
  7. JPanel panel1 = new JPanel();
  8. panel1.setPreferredSize(new Dimension(700, 45));
  9. panel1.setLayout(new GridLayout(1, 4));
  10. JLabel label1 = new JLabel("Name:");
  11. JTextField j1 = new JTextField("");
  12. JLabel label2 = new JLabel("Qualification:");
  13. JComboBox<Object> j2 = new JComboBox<>();
  14. j2.addItem("chuzhong");
  15. j2.addItem("gaozhong");
  16. j2.addItem("undergraduate");
  17. panel1.add(label1);
  18. panel1.add(j1);
  19. panel1.add(label2);
  20. panel1.add(j2);
  21.  
  22. JPanel panel2 = new JPanel();
  23. panel2.setPreferredSize(new Dimension(700, 65));
  24. panel2.setLayout(new GridLayout(1, 4));
  25. JLabel label3 = new JLabel("Address:");
  26. JTextArea j3 = new JTextArea();
  27. JLabel label4 = new JLabel("Hobby:");
  28. JPanel p = new JPanel();
  29. p.setLayout(new GridLayout(3, 1));
  30. p.setBorder(BorderFactory.createLineBorder(null));
  31. JCheckBox c1 = new JCheckBox("Reading");
  32. JCheckBox c2 = new JCheckBox("Singing");
  33. JCheckBox c3 = new JCheckBox("Dancing");
  34. p.add(c1);
  35. p.add(c2);
  36. p.add(c3);
  37. panel2.add(label3);
  38. panel2.add(j3);
  39. panel2.add(label4);
  40. panel2.add(p);
  41.  
  42. JPanel panel3 = new JPanel();
  43. panel3.setPreferredSize(new Dimension(700, 150));
  44. FlowLayout flowLayout1 = new FlowLayout(FlowLayout.LEFT, 70, 40);
  45. panel3.setLayout(flowLayout1);
  46. JLabel label5 = new JLabel("Sex:");
  47. JPanel p1 = new JPanel();
  48. p1.setLayout(new GridLayout(2,1));
  49. p1.setBorder(BorderFactory.createLineBorder(null));
  50. ButtonGroup bu = new ButtonGroup();
  51. JRadioButton jr1 = new JRadioButton("Male");
  52. JRadioButton jr2 = new JRadioButton("Female");
  53. bu.add(jr1);
  54. bu.add(jr2);
  55. p1.add(jr1);
  56. p1.add(jr2);
  57. panel3.add(label5);
  58. panel3.add(p1);
  59. add(panel1);
  60. add(panel2);
  61. add(panel3);
  62.  
  63. JPanel panel4 = new JPanel();
  64. panel4.setPreferredSize(new Dimension(700, 150));
  65. JButton b1 = new JButton("Validate");
  66. panel4.add(b1);
  67. JButton b2 = new JButton("Reset");
  68. panel4.add(b2);
  69. add(panel4);
  70.  
  71. FlowLayout flowLayout = new FlowLayout();
  72. this.setLayout(flowLayout);
  73. this.setTitle("Students Detail");
  74. this.setBounds(300, 300, 800, 400);
  75. this.setVisible(true);
  76. this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
  77.  
  78. b1.addActionListener(new ActionListener() {
  79.  
  80. public void actionPerformed(ActionEvent e) {
  81. // TODO 自动生成的方法存根
  82. String xueli = j2.getSelectedItem().toString();
  83. System.out.println("Name:" + j1.getText());
  84. System.out.println("Qualification:" + xueli);
  85. String hobbystring = "Hobby:";
  86. if (c1.isSelected()) {
  87. hobbystring += "Reading";
  88. }
  89. if (c2.isSelected()) {
  90. hobbystring += "Singing";
  91. }
  92. if (c3.isSelected()) {
  93. hobbystring += "Dancing";
  94. }
  95. System.out.println("Address:" + j3.getText());
  96. if (jr1.isSelected()) {
  97. System.out.println("Sex:Male");
  98. }
  99. if (jr2.isSelected()) {
  100. System.out.println("Sex:Female");
  101. }
  102. System.out.println(hobbystring);
  103. }
  104. });
  105. b2.addActionListener(new ActionListener() {
  106.  
  107. public void actionPerformed(ActionEvent e) {
  108. // TODO 自动生成的方法存根
  109. j1.setText(null);
  110. j3.setText(null);
  111. j2.setSelectedIndex(0);
  112. c1.setSelected(false);
  113. c2.setSelected(false);
  114. c3.setSelected(false);
  115. bu.clearSelection();
  116. }
  117. });
  118. }
  119.  
  120. public static void main(String args[]) {
  121. new DemoJFrame();
  122. }
  123.  
  124. }

DemoJFrame

结果如下:

重置:

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

  1. class Lefthand implements Runnable {
  2. public void run() {
  3. for (int i = 0; i < 5; i++) {
  4. System.out.println(i + 1 + ":first.你好!");
  5. try {
  6. Thread.sleep(500);
  7. } catch (InterruptedException e) {
  8. System.out.println("Lefthand error.");
  9. }
  10. }
  11. }
  12. }
  13.  
  14. class Righthand implements Runnable {
  15. public void run() {
  16. for (int i = 0; i < 5; i++) {
  17. System.out.println(i + 1 + ":second.你好!");
  18. try {
  19. Thread.sleep(300);
  20. } catch (InterruptedException e) {
  21. System.out.println("Righthand error.");
  22. }
  23. }
  24. }
  25. }
  26.  
  27. public class ThreadTest {
  28. public static void main(String[] args) {
  29. Runnable left = new Lefthand();
  30. Thread l = new Thread(left);
  31. Runnable right = new Righthand();
  32. Thread r = new Thread(right);
  33. l.start();
  34. r.start();
  35. }
  36. }

ThreadTest

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

1、

  1. package 身份证;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.File;
  5. import java.io.FileInputStream;
  6. import java.io.InputStreamReader;
  7. import java.io.FileNotFoundException;
  8. import java.io.IOException;
  9. import java.util.ArrayList;
  10. import java.util.Arrays;
  11. import java.util.Collections;
  12. import java.util.Scanner;
  13. import java.awt.*;
  14. import javax.swing.*;
  15. import java.awt.event.*;
  16.  
  17. public class Main extends JFrame {
  18. private static ArrayList<Student> studentlist;
  19. private static ArrayList<Student> list;
  20. private JPanel panel;
  21. private JPanel buttonPanel;
  22. private static final int DEFAULT_WITH = 900;
  23. private static final int DEFAULT_HEIGHT = 500;
  24.  
  25. public Main() {
  26. studentlist = new ArrayList<>();
  27. Scanner scanner = new Scanner(System.in);
  28. File file = new File("D:\\java\\身份证号.txt");
  29. try {
  30. FileInputStream fis = new FileInputStream(file);
  31. BufferedReader in = new BufferedReader(new InputStreamReader(fis));
  32. String temp = null;
  33. while ((temp = in.readLine()) != null) {
  34.  
  35. Scanner linescanner = new Scanner(temp);
  36.  
  37. linescanner.useDelimiter(" ");
  38. String name = linescanner.next();
  39. String number = linescanner.next();
  40. String sex = linescanner.next();
  41. String age = linescanner.next();
  42. String province = linescanner.nextLine();
  43. Student student = new Student();
  44. student.setName(name);
  45. student.setnumber(number);
  46. student.setsex(sex);
  47. int a = Integer.parseInt(age);
  48. student.setage(a);
  49. student.setprovince(province);
  50. studentlist.add(student);
  51.  
  52. }
  53. } catch (FileNotFoundException e) {
  54. System.out.println("学生信息文件找不到");
  55. e.printStackTrace();
  56. } catch (IOException e) {
  57. System.out.println("学生信息文件读取错误");
  58. e.printStackTrace();
  59. }
  60. panel = new JPanel();
  61. panel.setLayout(new BorderLayout());
  62. JTextArea jt = new JTextArea();
  63. panel.add(jt);
  64. add(panel, BorderLayout.NORTH);
  65. buttonPanel = new JPanel();
  66. buttonPanel.setLayout(new GridLayout(1, 8));
  67. JButton jButton = new JButton("字典排序");
  68. JButton jButton1 = new JButton("年龄最大和年龄最小");
  69. JLabel lab = new JLabel("查找你的同乡");
  70. JTextField jt1 = new JTextField();
  71. JLabel lab1 = new JLabel("查找与你年龄相近的人:");
  72. JTextField jt2 = new JTextField();
  73. JLabel lab2 = new JLabel("输入你的身份证号码:");
  74. JTextField jt3 = new JTextField();
  75. JButton jButton2 = new JButton("退出");
  76. jButton.setBounds(900, 200,100, 90);
  77. jButton1.setBounds(50, 120, 90, 60);
  78. jt1.setBounds(900, 120, 100, 80);
  79. jt2.setBounds(800, 200, 100, 80);
  80. jt3.setBounds(450, 120, 80, 90);
  81. jButton2.setBounds(800,200, 60, 50);
  82. jButton.addActionListener(new ActionListener() {
  83. public void actionPerformed(ActionEvent e) {
  84. Collections.sort(studentlist);
  85. jt.setText(studentlist.toString());
  86. }
  87. });
  88. jButton1.addActionListener(new ActionListener() {
  89. public void actionPerformed(ActionEvent e) {
  90. int max = 0, min = 100;
  91. int j, k1 = 0, k2 = 0;
  92. for (int i = 1; i < studentlist.size(); i++) {
  93. j = studentlist.get(i).getage();
  94. if (j > max) {
  95. max = j;
  96. k1 = i;
  97. }
  98. if (j < min) {
  99. min = j;
  100. k2 = i;
  101. }
  102.  
  103. }
  104. jt.setText("年龄最大:" + studentlist.get(k1) + "年龄最小:" + studentlist.get(k2));
  105. }
  106. });
  107. jButton2.addActionListener(new ActionListener() {
  108. public void actionPerformed(ActionEvent e) {
  109. dispose();
  110. System.exit(0);
  111. }
  112. });
  113. jt1.addActionListener(new ActionListener() {
  114. public void actionPerformed(ActionEvent e) {
  115. String find = jt1.getText();
  116. String text="";
  117. String place = find.substring(0, 3);
  118. for (int i = 0; i < studentlist.size(); i++) {
  119. if (studentlist.get(i).getprovince().substring(1, 4).equals(place)) {
  120. text+="\n"+studentlist.get(i);
  121. jt.setText("老乡:" + text);
  122. }
  123. }
  124. }
  125. });
  126. jt2.addActionListener(new ActionListener() {
  127. public void actionPerformed(ActionEvent e) {
  128. String yourage = jt2.getText();
  129. int a = Integer.parseInt(yourage);
  130. int near = agenear(a);
  131. int value = a - studentlist.get(near).getage();
  132. jt.setText("年龄相近:" + studentlist.get(near));
  133. }
  134. });
  135. jt3.addActionListener(new ActionListener() {
  136. public void actionPerformed(ActionEvent e) {
  137. list = new ArrayList<>();
  138. Collections.sort(studentlist);
  139. String key = jt3.getText();
  140. for (int i = 1; i < studentlist.size(); i++) {
  141. if (studentlist.get(i).getnumber().contains(key)) {
  142. list.add(studentlist.get(i));
  143. jt.setText("你或许是:\n" + list);
  144.  
  145. }
  146. }
  147. }
  148. });
  149. buttonPanel.add(jButton);
  150. buttonPanel.add(jButton1);
  151. buttonPanel.add(lab);
  152. buttonPanel.add(jt1);
  153. buttonPanel.add(lab1);
  154. buttonPanel.add(jt2);
  155. buttonPanel.add(lab2);
  156. buttonPanel.add(jt3);
  157. buttonPanel.add(jButton2);
  158. add(buttonPanel, BorderLayout.SOUTH);
  159. setSize(DEFAULT_WITH, DEFAULT_HEIGHT);
  160. }
  161.  
  162. public static int agenear(int age) {
  163. int min = 53, value = 0, k = 0;
  164. for (int i = 0; i < studentlist.size(); i++) {
  165. value = studentlist.get(i).getage() - age;
  166. if (value < 0)
  167. value = -value;
  168. if (value < min) {
  169. min = value;
  170. k = i;
  171. }
  172. }
  173. return k;
  174. }
  175.  
  176. }

Main

  1. package 身份证;
  2.  
  3. public class Student implements Comparable<Student> {
  4.  
  5. private String name;
  6. private String number ;
  7. private String sex ;
  8. private int age;
  9. private String province;
  10.  
  11. public String getName() {
  12. return name;
  13. }
  14. public void setName(String name) {
  15. this.name = name;
  16. }
  17. public String getnumber() {
  18. return number;
  19. }
  20. public void setnumber(String number) {
  21. this.number = number;
  22. }
  23. public String getsex() {
  24. return sex ;
  25. }
  26. public void setsex(String sex ) {
  27. this.sex =sex ;
  28. }
  29. public int getage() {
  30.  
  31. return age;
  32. }
  33. public void setage(int age) {
  34. // int a = Integer.parseInt(age);
  35. this.age= age;
  36. }
  37.  
  38. public String getprovince() {
  39. return province;
  40. }
  41. public void setprovince(String province) {
  42. this.province=province ;
  43. }
  44.  
  45. public int compareTo(Student o) {
  46. return this.name.compareTo(o.getName());
  47. }
  48.  
  49. public String toString() {
  50. return name+"\t"+sex+"\t"+age+"\t"+number+"\t"+province+"\n";
  51. }
  52. }

Student

  1. package 身份证;
  2.  
  3. import java.awt.*;
  4. import javax.swing.*;
  5.  
  6. public class ButtonText {
  7. public static void main(String[] args) {
  8. EventQueue.invokeLater(() -> {
  9. JFrame frame = new Main();
  10. frame.setTitle("身份证");
  11. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  12. frame.setVisible(true);
  13. });
  14. }
  15. }

ButtonText

2、

  1. package 答题;
  2.  
  3. import java.awt.*;
  4. import java.awt.event.*;
  5. import java.util.*;
  6. import java.util.Random;
  7. import javax.swing.*;
  8.  
  9. public class Exam extends JFrame {
  10. JPanel p=new JPanel();
  11. JLabel timeLabel=new JLabel();
  12.  
  13. JLabel[] label1=new JLabel[10];
  14. JLabel[] label2=new JLabel[10];
  15. JLabel[] label3=new JLabel[10];
  16. JLabel[] label4=new JLabel[10];
  17. JLabel[] label5=new JLabel[10];
  18. JTextField[] field=new JTextField[10];
  19. JLabel[] label6=new JLabel[10];
  20. String[] btn_name= {"开始","重置","提交","重考"};
  21. JButton[] btn=new JButton[4];
  22. Panel2 panel2=null;
  23. int ExamCount=0;
  24. JLabel examLabel=new JLabel();
  25. double[] result=new double[10];
  26. public static void main(String[] args) {
  27. new Exam("测试").setVisible(true);
  28. }
  29.  
  30. public Exam(String title) {
  31. setTitle(title);
  32. setLocationRelativeTo(null);
  33. setDefaultCloseOperation(3);
  34. setSize(400,500);
  35. setResizable(false);
  36. setForeground(Color.blue);
  37. add(new Panel1(),BorderLayout.NORTH);
  38. panel2=new Panel2();
  39. add(new JScrollPane(panel2));
  40. add(new Panel3(),BorderLayout.WEST);
  41. }
  42.  
  43. int rightResultCount=0;
  44. public void startExam() {
  45. int num1=0;
  46. int num2=0;
  47. String[] quots= {"+","-","*","/"};
  48. String quot=null;
  49. Random ran=null;
  50. ran=new Random(System.currentTimeMillis());
  51. Box box=Box.createVerticalBox();
  52.  
  53. for(int i=0;i<10;i++) {
  54. num1=ran.nextInt(100)+1;
  55. num2=ran.nextInt(100)+1;
  56. int n=ran.nextInt(4);
  57. quot=new String(quots[n]);
  58. switch(quot) {
  59. case "+":
  60. result[i]=num1+num2;
  61. break;
  62. case "-":
  63. result[i]=num1-num2;
  64. break;
  65. case "*":
  66. result[i]=num1*num2;
  67. break;
  68. case "/":
  69. result[i]=num1/(num2*1.0);
  70. result[i]=Math.round(result[i]*100)/100.0;
  71. break;
  72. }
  73.  
  74. label1[i]=new JLabel("第"+(i+1)+"题:");
  75. label2[i]=new JLabel(num1+"");
  76.  
  77. label3[i]=new JLabel(quot);
  78. label4[i]=new JLabel(num2+"");
  79. label5[i]=new JLabel("=");
  80. field[i]=new JTextField();
  81. field[i].setPreferredSize(new Dimension(60,20));
  82. field[i].addKeyListener(new KeyAdapter() {
  83. public void keyTyped(KeyEvent ee) {
  84. if((ee.getKeyChar()>'9' || ee.getKeyChar()<'0') && ee.getKeyChar()!=45 && ee.getKeyChar()!='.') {
  85. ee.consume();
  86. }
  87. }
  88. });
  89. label6[i]=new JLabel("");
  90. Box hbox=Box.createHorizontalBox();
  91. hbox.add(label1[i]);
  92. hbox.add(Box.createHorizontalStrut(20));
  93. hbox.add(label2[i]);
  94. hbox.add(Box.createHorizontalStrut(5));
  95. hbox.add(label3[i]);
  96. hbox.add(Box.createHorizontalStrut(5));
  97. hbox.add(label4[i]);
  98. hbox.add(Box.createHorizontalStrut(5));
  99. hbox.add(label5[i]);
  100. hbox.add(Box.createHorizontalStrut(5));
  101. hbox.add(field[i]);
  102. hbox.add(Box.createHorizontalStrut(20));
  103. hbox.add(label6[i]);
  104. box.add(hbox);
  105. box.add(Box.createVerticalStrut(20));
  106. }
  107. panel2.add(box);
  108. panel2.validate();
  109. }
  110. int submitCount=0;
  111. class Listener implements ActionListener{
  112. public void actionPerformed(ActionEvent e) {
  113. JButton button=(JButton)e.getSource();
  114. if(button==btn[0]) {
  115. startExam();
  116. ExamCount++;
  117. btn[0].setEnabled(false);
  118.  
  119. for(int i=1;i<4;i++) {
  120. btn[i].setEnabled(true);
  121. }
  122. }
  123. if(button==btn[1]) {
  124. for(int i=0;i<10;i++) {
  125. field[i].setText("");
  126. }
  127. }
  128. if(button==btn[2] ) {
  129. rightResultCount=0;
  130. btn[2].setEnabled(false);
  131. double yourResult=0;
  132. for(int i=0;i<10;i++) {
  133. try {
  134. yourResult=Double.parseDouble(field[i].getText().trim());
  135. }catch(Exception ee) {}
  136.  
  137. if(yourResult==result[i]) {
  138. rightResultCount++;
  139. label6[i].setText("V");
  140. label6[i].setForeground(Color.BLUE);
  141.  
  142. }else {
  143. label6[i].setText("X");
  144. label6[i].setForeground(Color.RED);
  145.  
  146. }
  147. }
  148. examLabel.setText("你答对了 "+rightResultCount+
  149. " 道题,答错了"+(10-rightResultCount)+" 道题!"+
  150. "考试得分是: "+rightResultCount*10+" 分!");
  151. }
  152. if(button==btn[3]) {
  153. btn[2].setEnabled(true);
  154. panel2.removeAll();
  155. startExam();
  156. ExamCount++;
  157. btn[3].setEnabled(false);
  158. for(int i=0;i<10;i++) {
  159. field[i].setText("");
  160. label6[i].setText("");
  161. }
  162. panel2.repaint();
  163. }
  164. if(btn[2].isEnabled()==false && btn[3].isEnabled()==false) {
  165. btn[1].setEnabled(false);
  166. }
  167. }
  168. }
  169.  
  170. class Panel1 extends JPanel{
  171. public Panel1() {
  172. setPreferredSize(new Dimension(350,120));
  173. setLayout(new GridLayout(3,1,10,10));
  174. JTextArea area=new JTextArea("点击“开始”开始答题,答案中有小数的,保留2位!");
  175. area.setLineWrap(true);
  176. area.setEditable(false);
  177. add(area);
  178. add(examLabel);
  179. p.add(timeLabel);
  180. add(p);
  181. }
  182. }
  183.  
  184. class Panel2 extends JPanel{
  185. public Panel2() {
  186. setPreferredSize(new Dimension(400,600));
  187. }
  188. }
  189.  
  190. class Panel3 extends JPanel{
  191. public Panel3() {
  192. setPreferredSize(new Dimension(50,100));
  193. setBackground(Color.LIGHT_GRAY);
  194. for(int i=0;i<4;i++) {
  195. btn[i]=new JButton(btn_name[i]);
  196. btn[i].addActionListener(new Listener());
  197. add(btn[i]);
  198. if(i>0) {
  199. btn[i].setEnabled(false);
  200. }
  201. }
  202. }
  203. }
  204. }

三、总结

本周我们学习了有关线程的知识,了解了什么是多线程及其好处,编程实验在学长的演示和上课老师的讲解下,也做出来了,对于理论知识,还得多看书来熟记。

201771010135 杨蓉庆《面对对象程序设计(java)》第十六周学习总结的更多相关文章

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

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

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

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

  3. 201771010135杨蓉庆《面向对象程序设计(java)》第四周学习总结

    学习目标 1.掌握类与对象的基础概念,理解类与对象的关系: 2.掌握对象与对象变量的关系: 3.掌握预定义类的基本使用方法,熟悉Math类.String类.math类.Scanner类.LocalDa ...

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

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

  5. 201771010135杨蓉庆 《面向对象程序设计(java)》第三周学习总结

    一:第1-3章学习内容: 第一章:复习基本数据类型 整型 byte(1个字节 表示范围:-2^7 ~ (2^7)-1) short(2个字节 表示范围:-2^15~(2^15)-1) int(4个字节 ...

  6. 201771010135杨蓉庆《面向对象程序设计(java)》第六周学习总结

    实验六 继承定义与使用 1.实验目的与要求 (1) 理解继承的定义: (2) 掌握子类的定义要求 (3) 掌握多态性的概念及用法: (4) 掌握抽象类的定义及用途: (5) 掌握类中4个成员访问权限修 ...

  7. 201771010135杨蓉庆《面向对象程序设计(java)》第二周学习总结

    第一部分:理论知识学习部分 3.1 标识符:由字母.下划线.美元符号和数字组成, 且第一个符号不能为数字,可用作:类名.变量名.方法名.数组名.文件名等.有Hello.$1234.程序名.www_12 ...

  8. 201771010134杨其菊《面向对象程序设计(java)》第十六周学习总结

    第十六周学习总结 第一部分:理论知识 1. 程序是一段静态的代码,它是应用程序执行的蓝本.进程是程序的一次动态执行,它对应了从代码加载.执行至执行完毕的一个完整过程.操作系统为每个进程分配一段独立的内 ...

  9. 201521123061 《Java程序设计》第十二周学习总结

    201521123061 <Java程序设计>第十二周学习总结 1. 本周学习总结 1.1 以你喜欢的方式(思维导图或其他)归纳总结多流与文件相关内容. 2. 书面作业 将Student对 ...

  10. 201521123072《java程序设计》第十二周学习总结

    201521123072<java程序设计>第十二周学习总结 1. 本周学习总结 1.1 以你喜欢的方式(思维导图或其他)归纳总结多流与文件相关内容. 2. 书面作业 将Student对象 ...

随机推荐

  1. Linux - Shell - 算数表达式 - 位运算

    概述 shell 中基于 $(()) 的 位运算 背景 复习 shell 脚本 凑数吧 准备 环境 os centos7 1. 位运算 代码 #!/bin/bash # 位运算 arg1=2 arg2 ...

  2. python3练习100题——005

    继续做题-答案都会经过py3测试原题网址:http://www.runoob.com/python/python-exercise-example5.html 题目:输入三个整数x,y,z,请把这三个 ...

  3. django 搭建一个投票类网站(二)

    前一篇讲了创建一个工程和一个polls的应用程序,以及配置了数据库. 这篇就继续讲吧 1.django admin模块 admin模块是django自带的模块,他让开发者可以不用管写任何代码的情况下就 ...

  4. json_encode中文不转义问题

    //php5.3之后才有这个参数,这样存入数据库中的中文json数据就不会转义,也能被正确解析1JSON_UNESCAPED_UNICODE(中文不转为unicode ,对应的数字 256) JSON ...

  5. 将图片中的一部分图片用ps进行旋转

    先用选择工具选择你要进行变动的那部分图像,至于选择的方法有多种而且得看你的图片来决定采取何种选择方法.然后在英文输入状态下按下“CTRL+T”出现变换框,你将鼠标移动对角点上,当鼠标变为一种旋转的图标 ...

  6. NW.js桌面应用开发(一)

    NWjs中文网 Electron中文网 一些需要了解的历史与特性,其实就是 NW.js 和 Electron的争议,建议还是亲自阅读一下各自的官网说明 1.下载SDK版工具 从淘宝NPM镜像下载,速度 ...

  7. Python爬取ithome的一所有新闻标题评论数及其他一些信息并存入Excel中。

    # coding=utf-8 import numpy as np import pandas as pd import sys from selenium import webdriver impo ...

  8. Mybaits(11)延迟加载

    一.概述 1.概念 就是在需要用到数据时才去进行加载,不需要用的数据就不加载数据.延迟加载也称为懒加载. 2.优缺点 优点:先从单表查询,需要时再从关联表去关联查询,大大提高数据库性能,因为查询单表要 ...

  9. 需要再次删除清空部署才能用rancher部署成功的是docker有问题

    需要再次删除清空部署才能用rancher部署成功的是docker有问题 待办 可以解释为什么一定要用特定的docker版本

  10. 微信h5游戏如何在微信中做好域名防封 防屏蔽的 工作

    最近微信开始大封杀,不知道原因是什么,可能是因为违规网站太多了吧,很多网站都被错杀了,下面我们聊一下怎样才能避免域名被封杀呢. 在各种不同的域名当中,能够做出了更适合的选择,这些对于大家域名防封_域名 ...