一:理论部分

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接口创建线程的方法。

程序如下:

class Lefthand extends Thread {
public void run()
{
for(int i=;i<=;i++)
{ System.out.println("You are Students!");
try{ sleep(); }
catch(InterruptedException e)
{ System.out.println("Lefthand error.");}
}
}
}
class Righthand extends Thread {
public void run()
{
for(int i=;i<=;i++)
{ System.out.println("I am a Teacher!");
try{ sleep(); }
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();
}
}

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

class Lefthand implements Runnable {
public void run()
{
for(int i=;i<=;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=;i<=;i++)
{ System.out.println("I am a Teacher!");
try{ Thread.sleep();//休眠300毫秒
}
catch(InterruptedException e)
{ System.out.println("Righthand error.");}
}
} }
public class ThreadTest
{
public static void main(String[] args)
{ Righthand righthand = new Righthand();//新建一个righthand对象
Lefthand lefthand = new Lefthand();//新建一个lefthand对象
Thread right = new Thread(righthand);//start方法在Thread类中,新建Thread类
right.start();
Thread left=new Thread(lefthand);
left.start();
}
}

程序运行结果如下:

测试程序2:

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

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

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

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

程序如下:

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

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 = ;
private static final int DEFAULT_HEIGHT = ; 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); // 擦除背景
Graphics2D g2 = (Graphics2D) g;
for (Ball b : balls)
{
g2.fill(b.getShape());
}
} public Dimension getPreferredSize()
{
return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT); }
}
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 = ;
public static final int DELAY = ; /**
* 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());//在窗口添加两个按钮
addButton(buttonPanel, "Close", event -> System.exit());
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 = ; i <= STEPS; i++)
{
ball.move(comp.getBounds());
comp.paint(comp.getGraphics());
Thread.sleep(DELAY);
}
}
catch (InterruptedException e)
{
}
}
}
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 = ;
private static final int YSIZE = ;
private double x = ;
private double y = ;
private double dx = ;
private double dy = ; /**
* 将球移动到下一个位置,如果球碰到其中一条边,则反向移动
*/
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);
}
}

运行结果如下:

14-4:

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 = ;
public static final int DELAY = ; /**
* 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());
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 = ; i <= STEPS; i++)
{
ball.move(comp.getBounds());
comp.repaint();
Thread.sleep(DELAY);
}
}
catch (InterruptedException e)
{
}
};
Thread t = new Thread(r);
t.start();//调用Thread类中的start方法
}
}
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 = ;
private static final int DEFAULT_HEIGHT = ; 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.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 = ;
private static final int YSIZE = ;
private double x = ;
private double y = ;
private double dx = ;
private double dy = ; /**
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);
}
}

程序运行结果如下:

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

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

程序运行结果如下:

测试程序4

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

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

package unsynch;

/**
* This program shows data corruption when multiple threads access a data structure.
* @version 1.31 2015-06-21
* @author Cay Horstmann
*/
public class UnsynchBankTest
{
public static final int NACCOUNTS = ;
public static final double INITIAL_BALANCE = ;//期初余额
public static final double MAX_AMOUNT = ;//最大数量
public static final int DELAY = ;//延时 public static void main(String[] args)
{
Bank bank = new Bank(NACCOUNTS, INITIAL_BALANCE);
for (int i = ; 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.*;

/**
* A bank with a number of bank accounts.
* @version 1.30 2004-08-01
* @author Cay Horstmann
*/
public class Bank
{
private final double[] accounts; /**
* Constructs the bank.
* @param n the number of accounts
* @param initialBalance the initial balance for each account
*/
public Bank(int n, double initialBalance)
{
accounts = new double[n];
Arrays.fill(accounts, initialBalance);
} /**
* Transfers money from one account to another.
* @param from the account to transfer from
* @param to the account to transfer to
* @param amount the amount to transfer
*/
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());
} /**
* Gets the sum of all account balances.
* @return the total balance
*/
public double getTotalBalance()
{
double sum = ; for (double a : accounts)
sum += a; return sum;
} /**
* Gets the number of accounts in the bank.
* @return the number of accounts
*/
public int size()
{
return accounts.length;
}
}

运行结果:

综合编程练习

编程练习1

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

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

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

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

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

程序如下:

import java.awt.EventQueue;

import javax.swing.JFrame;

public class Mian {
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
DemoJFrame page = new DemoJFrame();
});
}
}
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.LayoutManager;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask; import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.ButtonModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField; public class DemoJFrame extends JFrame {
private JPanel jPanel1;
private JPanel jPanel2;
private JPanel jPanel3;
private JPanel jPanel4;
private JTextField fieldname;
private JComboBox comboBox;
private JTextField fieldadress;
private ButtonGroup bg;
private JRadioButton nan;
private JRadioButton nv;
private JCheckBox sing;
private JCheckBox dance;
private JCheckBox draw; public DemoJFrame() {
// 设置窗口大小
this.setSize(, );
// 设置可见性
this.setVisible(true);
// 设置标题
this.setTitle("Student Detail");
// 设置关闭操作
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
// 设置窗口居中
WinCenter.center(this);
// 创建四个面板对象
jPanel1 = new JPanel();
setJPanel1(jPanel1);
jPanel2 = new JPanel();
setJPanel2(jPanel2);
jPanel3 = new JPanel();
setJPanel3(jPanel3);
jPanel4 = new JPanel();
setJPanel4(jPanel4);
// 设置容器为流式布局
FlowLayout flowLayout = new FlowLayout();
this.setLayout(flowLayout);
// 将四个面板添加到容器中
this.add(jPanel1);
this.add(jPanel2);
this.add(jPanel3);
this.add(jPanel4); } /*
* 设置面板一
*/
private void setJPanel1(JPanel jPanel) {
jPanel.setPreferredSize(new Dimension(, ));//设置此组件的首选大小
// 给面板的布局设置为网格布局 一行4列
jPanel.setLayout(new GridLayout(, ));
JLabel name = new JLabel("Name:");
name.setSize(, );
fieldname = new JTextField("");
fieldname.setSize(, );
JLabel study = new JLabel("Qualification:");
comboBox = new JComboBox();
comboBox.addItem("Graduate");
comboBox.addItem("senior");
comboBox.addItem("Undergraduate");
jPanel.add(name);
jPanel.add(fieldname);
jPanel.add(study);
jPanel.add(comboBox); } /*
* 设置面板二
*/
private void setJPanel2(JPanel jPanel) {
jPanel.setPreferredSize(new Dimension(, ));
// 给面板的布局设置为网格布局 一行4列
jPanel.setLayout(new GridLayout(, ));
JLabel name = new JLabel("Address:");
fieldadress = new JTextField();
fieldadress.setPreferredSize(new Dimension(, ));
JLabel study = new JLabel("Hobby:");
JPanel selectBox = new JPanel();
selectBox.setBorder(BorderFactory.createTitledBorder(""));
selectBox.setLayout(new GridLayout(, ));
sing = new JCheckBox("Singing");
dance = new JCheckBox("Dancing");
draw = new JCheckBox("Reading");
selectBox.add(sing);
selectBox.add(dance);
selectBox.add(draw);
jPanel.add(name);
jPanel.add(fieldadress);
jPanel.add(study);
jPanel.add(selectBox);
} /*
* 设置面板三
*/
private void setJPanel3(JPanel jPanel) {
jPanel.setPreferredSize(new Dimension(, ));
FlowLayout flowLayout = new FlowLayout(FlowLayout.LEFT);
jPanel.setLayout(flowLayout);
JLabel sex = new JLabel("Sex:");
JPanel selectBox = new JPanel();
selectBox.setBorder(BorderFactory.createTitledBorder(""));
selectBox.setLayout(new GridLayout(, ));
bg = new ButtonGroup();
nan = new JRadioButton("Male");
nv = new JRadioButton("Female");
bg.add(nan);
bg.add(nv);
selectBox.add(nan);
selectBox.add(nv);
jPanel.add(sex);
jPanel.add(selectBox); } /*
* 设置面板四
*/
private void setJPanel4(JPanel jPanel) {
// TODO 自动生成的方法存根
jPanel.setPreferredSize(new Dimension(, ));
FlowLayout flowLayout = new FlowLayout(FlowLayout.CENTER, , );
jPanel.setLayout(flowLayout);
jPanel.setLayout(flowLayout);
JButton sublite = new JButton("Validate");
JButton reset = new JButton("Reset");
sublite.addActionListener((e) -> valiData());
reset.addActionListener((e) -> Reset());
jPanel.add(sublite);
jPanel.add(reset);
} /*
* 提交数据
*/
private void valiData() {
// 拿到数据
String name = fieldname.getText().toString().trim();
String xueli = comboBox.getSelectedItem().toString().trim();
String address = fieldadress.getText().toString().trim();
System.out.println(name);
System.out.println(xueli);
String hobbystring="";
if (sing.isSelected()) {
hobbystring+="Singing ";
}
if (dance.isSelected()) {
hobbystring+="Dancing ";
}
if (draw.isSelected()) {
hobbystring+="Reading ";
}
System.out.println(address);
if (nan.isSelected()) {
System.out.println("Male");
}
if (nv.isSelected()) {
System.out.println("Female");
}
System.out.println(hobbystring);
} /*
* 重置
*/
private void Reset() {
fieldadress.setText(null);
fieldname.setText(null);
comboBox.setSelectedIndex();
sing.setSelected(false);
dance.setSelected(false);
draw.setSelected(false);
bg.clearSelection();
}
}
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.Window; public class WinCenter {
public static void center(Window win){
Toolkit tkit = Toolkit.getDefaultToolkit();//获取默认工具包
Dimension sSize = tkit.getScreenSize();//获取屏幕的大小
Dimension wSize = win.getSize();
if(wSize.height > sSize.height){
wSize.height = sSize.height;
}
if(wSize.width > sSize.width){
wSize.width = sSize.width;
}
win.setLocation((sSize.width - wSize.width)/ , (sSize.height - wSize.height)/ );//将组件移到新的位置
}
}

运行结果:

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

package test2;
class Lefthand extends Thread { public void run() { for(int i=;i<=;i++) { System.out.println("1.你好"); try{ sleep(); } catch(InterruptedException e) { System.out.println("Lefthand error.");} } } } class Righthand extends Thread { public void run() { for(int i=;i<=;i++) { System.out.println("2.你好"); try{ sleep(); } catch(InterruptedException e) { System.out.println("Righthand error.");} } } } public class AAAA { static Lefthand left; static Righthand right; public static void main(String[] args) { left=new Lefthand(); right=new Righthand(); left.start(); right.start(); } }

运行结果:

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

实验一:

import java.awt.*;
import javax.swing.*; public class CardTest {
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
JFrame frame = new Main();
frame.setTitle("身份证");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
}
public class Card implements Comparable<Card> {
private String name;
private String id;
private String sex;
private int age;
private String area; public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public String getId() {
return id;
} public void setId(String id) {
this.id = id;
} public String getSex() {
return sex;
} public void setSex(String sex) {
this.sex = sex;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} public String getArea() {
return area;
} public void setArea(String area) {
this.area = area;
} public int compareTo(Card c) {
return this.name.compareTo(c.getName());
} public String toString() {
return name + "\t" + id + "\t" + sex + "\t" + age + "\t" + area + "\n";
}
}
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*; public class Main extends JFrame {
private static ArrayList<Card> cardlist;
private static ArrayList<Card> list;
private JPanel panel;
private JPanel Panel1;
private static final int DEFAULT_WITH = ;
private static final int DEFAULT_HEIGHT = ; public Main() {
cardlist = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
File file = new File("E:\\身份证号.txt");
try {
FileInputStream fis = new FileInputStream(file);
BufferedReader in = new BufferedReader(new InputStreamReader(fis));
String temp = null; while ((temp = in.readLine()) != null) {
Scanner linescanner = new Scanner(temp);
linescanner.useDelimiter(" ");
String name = linescanner.next();
String id = linescanner.next();
String sex = linescanner.next();
String age = linescanner.next();
String area = linescanner.nextLine(); Card card = new Card();
card.setName(name);
card.setId(id);
card.setSex(sex);
int a = Integer.parseInt(age);
card.setAge(a);
card.setArea(area); cardlist.add(card);
} } catch (FileNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("信息文件找不到");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("信息文件读取错误");
e.printStackTrace();
}
panel = new JPanel();
panel.setLayout(new BorderLayout());
JTextArea jt = new JTextArea();
panel.add(jt);
add(panel, BorderLayout.NORTH);
Panel1 = new JPanel();
Panel1.setLayout(new GridLayout(, ));
JButton jButton = new JButton("字典排序");
JButton jButton1 = new JButton("年龄最大和年龄最小");
JLabel lab = new JLabel("寻找老乡:", Label.LEFT);
JTextField jt1 = new JTextField();
JLabel lab1 = new JLabel("寻找年龄相近的人:", Label.LEFT);
JTextField jt2 = new JTextField();
JLabel lab2 = new JLabel("输入你的身份证号码:", Label.LEFT);
JTextField jt3 = new JTextField();
JButton jButton2 = new JButton("退出"); jButton.addActionListener(new ActionListener() { @Override
public void actionPerformed(ActionEvent e) {
// TODO 自动生成的方法存根
Collections.sort(cardlist);
jt.setText(cardlist.toString()); }
}); jButton1.addActionListener(new ActionListener() { @Override
public void actionPerformed(ActionEvent e) {
// TODO 自动生成的方法存根
int max = , min = ;
int j, k1 = , k2 = ;
for (int i = ; i < cardlist.size(); i++) {
j = cardlist.get(i).getAge();
if (j > max) {
max = j;
k1 = i;
}
if (j < min) {
min = j;
k2 = i;
}
}
jt.setText("年龄最大:" + cardlist.get(k1) + "年龄最小:" + cardlist.get(k2));
}
}); jButton2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
System.exit();
}
});
jt1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String find = jt1.getText();
String text = "";
String place = find.substring(, );
for (int i = ; i < cardlist.size(); i++) {
if (cardlist.get(i).getArea().substring(, ).equals(place)) {
text += "\n" + cardlist.get(i);
jt.setText("老乡:" + text);
}
}
}
});
jt2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String yourage = jt2.getText();
int a = Integer.parseInt(yourage);
int near = agenear(a);
jt.setText("年龄相近:" + cardlist.get(near));
}
});
jt3.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
// TODO 自动生成的方法存根
list = new ArrayList<>();
Collections.sort(cardlist);
String key = jt3.getText();
for (int i = ; i < cardlist.size(); i++) {
if (cardlist.get(i).getId().contains(key)) {
list.add(cardlist.get(i));
jt.setText("你可能是:\n" + list);
}
}
}
});
Panel1.add(jButton);
Panel1.add(jButton1);
Panel1.add(lab);
Panel1.add(jt1);
Panel1.add(lab1);
Panel1.add(jt2);
Panel1.add(lab2);
Panel1.add(jt3);
Panel1.add(jButton2);
add(Panel1, BorderLayout.SOUTH);
setSize(DEFAULT_WITH, DEFAULT_HEIGHT);
} public static int agenear(int age) {
int j = , min = , value = , k = ;
for (int i = ; i < cardlist.size(); i++) {
value = cardlist.get(i).getAge() - age;
if (value < )
value = -value;
if (value < min) {
min = value;
k = i;
}
}
return k;
}
}

实验二:

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*; public class Demo extends JFrame {
int i = , i1 = , k = , sum = ;
private PrintWriter out = null;
private String[] c1 = new String[];
private String[] c2 = new String[]; public Demo() {
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(, ));
JTextArea jt1 = new JTextArea();
JTextField jt2 = new JTextField();
JTextArea jt3 = new JTextArea();
panel.add(jt1);
panel.add(jt2);
panel.add(jt3);
add(panel, BorderLayout.NORTH); JPanel panel1 = new JPanel();
panel1.setLayout(new GridLayout(, ));
Button button1 = new Button("生成题目"); Button button2 = new Button("生成文件");
panel1.add(button1);
panel1.add(button2); add(panel1, BorderLayout.SOUTH);
setSize(, );
button1.addActionListener(new ActionListener() { @Override
public void actionPerformed(ActionEvent e) {
// TODO 自动生成的方法存根
jt2.setText(null);
jt3.setText(null);
if (i < ) {
int a = (int) (Math.random() * );
int b = (int) (Math.random() * );
int m = (int) Math.round(Math.random() * );
switch (m) {
case :
while (b == || a % b != ) {
b = (int) Math.round(Math.random() * );
a = (int) Math.round(Math.random() * );
}
jt1.setText(i + + ": " + a + "/" + b + "=");
c1[i] = jt1.getText();
k = a / b;
i++;
break;
case :
jt1.setText(i + + ": " + a + "*" + b + "=");
c1[i] = jt1.getText();
k = a * b;
i++;
break;
case :
jt1.setText(i + + ": " + a + "+" + b + "=");
c1[i] = jt1.getText();
k = a + b;
i++;
break;
case :
while (a < b) {
int x = a;
a = b;
b = x;
}
jt1.setText(i + + ": " + a + "-" + b + "=");
c1[i] = jt1.getText();
k = a - b;
i++;
break;
}
}
}
});
jt2.addActionListener(new ActionListener() { @Override
public void actionPerformed(ActionEvent e) {
// TODO 自动生成的方法存根
if (i < ) {
int find = Integer.parseInt(jt2.getText());
String d = jt2.getText().toString().trim();
if (jt2.getText() != "") {
if (find == k) {
sum += ;
jt3.setText("答案正确");
} else
jt3.setText("答案错误");
}
c2[i1] = d;
i1++;
}
}
});
button2.addActionListener(new ActionListener() { @Override
public void actionPerformed(ActionEvent e) {
// TODO 自动生成的方法存根
try {
out = new PrintWriter("text.txt");
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
for (int counter = ; counter < ; counter++) {
out.println(c1[counter] + c2[counter]);
}
out.println("成绩为" + sum);
out.close();
}
});
}
}
import java.awt.*;
import javax.swing.*; public class DemoTest {
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
JFrame frame = new Demo();
frame.setTitle("计算题");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
}

三:实验总结

这周主要学习了线程,线程是程序中一个单一的顺序从控制流程。在学习过程中,了解了线程创建的两种技术:用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. Imagelab-0-QT label显示 opencv 图像

    Imagelab-0-QT label显示 opencv 图像 opencvc++qtimagelab 开始之前 这其实也是opencv 处理图像的系列, 只是想我们在进一步复杂化我们的代码之前, 每 ...

  2. apache、nginx配置openssl自签名证书

    1.生成私钥 生成rsa私钥,des3算法,2048位强度.server.key是秘钥文件名,需要提供一个至少4位的密码. [root@localhost ~]# openssl genrsa -de ...

  3. OSChina 周一乱弹 —— 为什么人类和人工智能定要一战

    2019独角兽企业重金招聘Python工程师标准>>> Osc乱弹歌单(2018)请戳(这里) [今日歌曲] @小小编辑:推荐歌曲,又失恋了 - 花粥 <又失恋了>- 花 ...

  4. 通过例题进一步学习DP

    1.以上篇文章数塔为例 https://blog.csdn.net/weixin_43627118/article/details/88701586 上一章用的是递归的做法,这次我们采用递推的做法. ...

  5. python json.dumps中ensure_ascii的使用,load与loads的区别

    json模块最常用的两个功能: 一:json.dumps(),用于将dict拆分成str格式,称为序列化,注意序列化后,虽然print出来仍然显示的字典的样子,但是此时已经是str类型了. 其中,有时 ...

  6. 【Java8新特性】你知道Java8为什么要引入Lambda表达式吗?

    写在前面 这是一道真实的面试题,一个读者朋友出去面试,面试官竟然问他这样一个问题:你说说Java8中为什么引入Lambda表达式?引入Lambda表达式后有哪些好处呢?还好这个朋友对Java8早有准备 ...

  7. 服务器安装JDK

    1.卸载OpenJDK, 安装OracleJDK a.一般的LINUX发行版内置OpenJDK, 相当于JDK的开源版本(我们平时使用的JDK特指OracleJDK) b.OpenJDK 不能使用ja ...

  8. thinkphp历史漏洞

    https://github.com/pochubs/pochubs/blob/master/ThinkPHP.md tp 历史漏洞 路由控制類RCE/think/App.php if (!preg_ ...

  9. V - Can you answer these queries? HDU - 4027 线段树 暴力

    V - Can you answer these queries? HDU - 4027 这个题目开始没什么思路,因为不知道要怎么去区间更新这个开根号. 然后稍微看了一下题解,因为每一个数开根号最多开 ...

  10. python学习笔记-零碎知识点

    1. 绝对值 abs(-4) 结果: 4 2.