狄慧201771010104《面向对象程序设计(java)》第十六周学习总结
实验十六 线程技术
实验时间 2017-12-8
一、知识点总结:
1、程序与进程的概念
‐程序是一段静态的代码,它是应用程序执行的蓝本。
‐进程是程序的一次动态执行,它对应了从代码加载、执行至执行完毕的一个完整过程。
‐操作系统为每个进程分配一段独立的内存空间和系统资源,包括:代码数据以及堆栈等资源。每 一个进程的内部数据和状态都是完全独立的。
‐多任务操作系统中,进程切换对CPU资源消耗较大。
2、多线程的概念
‐多线程是进程执行过程中产生的多条执行线索。
‐线程是比进程执行更小的单位。
‐线程不能独立存在,必须存在于进程中,同一进程的各线程间共享进程空间的数据。
‐每个线程有它自身的产生、存在和消亡的过程, 是一个动态的概念。
‐多线程意味着一个程序的多行语句可以看上去几 乎在同一时间内同时运行。
‐线程创建、销毁和切换的负荷远小于进程,又称为轻量级进程(lightweight process)。
3、Java实现多线程有两种途径:
‐创建Thread类的子类
‐在程序中定义实现Runnable接口的类
4、用Thread类子类创建线程
首先需从Thread类派生出一个子类,在该子类中重写run()方法。
class hand extends Thread
{
public void run()
{……}
}
5、用Thread类的子类创建多线程的关键性操作
–定义Thread类的子类并实现用户线程操作,即 run()方法的实现。
–在适当的时候启动线程。
由于Java只支持单重继承,用这种方法定义的类不可再继承其他父类。
6、用Runnable()接口实现线程
- 首先设计一个实现Runnable接口的类;
- 然后在类中根据需要重写run方法;
- 再创建该类对象,以此对象为参数建立Thread 类的对象;
- 调用Thread类对象的start方法启动线程,将 CPU执行权转交到run方法。
7、线程的终止
-当线程的run方法执行方法体中最后一条语句后,或者出现了在run方法中没有捕获的异常时,线程将终止,让出CPU使用权。
- 调用interrupt()方法也可终止线程。
void interrupt()
– 向一个线程发送一个中断请求,同时把这个线程的“interrupted”状态置为true。
– 若该线程处于 blocked 状态 ,会抛出 InterruptedException。
8、测试线程是否被中断的方法
Java提供了几个用于测试线程是否被中断的方法。
-static boolean interrupted()
– 检测当前线程是否已被中断 ,并重置状态 “interrupted”值为false。
-boolean isInterrupted()
– 检测当前线程是否已被中断 ,不改变状态 “interrupted”值 。
9、线程的状态
-利用各线程的状态变换,可以控制各个线程轮流使用CPU,体现多线程的并行性特征。
-线程有如下7种状态:
➢ New (新建)
➢ Runnable (可运行)
➢ Running(运行)
➢ Blocked (被阻塞)
➢ Waiting (等待)
➢ Timed waiting (计时等待)
➢ Terminated (被终止)
10、新创建线程
-new(新建)
线程对象刚刚创建,还没有启动,此时线程还处于不可运行状态。例如: Thread thread=new Thread(r); 此时线程thread处于新建状态,有了相应的内存空间以及其它资源。
11、可运行线程
- runnable(可运行状态)
➢ 此时线程已经启动,处于线程的run()方法之中。
➢ 此时的线程可能运行,也可能不运行,只要 CPU一空闲,马上就会运行。
➢ 调用线程的start()方法可使线程处于“可运行”状态。例如: thread.start();
12、被阻塞线程和等待线程
- blocked (被阻塞)
➢ 一个正在执行的线程因特殊原因,被暂停执行, 进入阻塞状态。
➢ 阻塞时线程不能进入队列排队,必须等到引起阻塞的原因消除,才可重新进入排队队列。
➢ 引起阻塞的原因很多,不同原因要用不同的方法解除。
-sleep(),wait()是两个常用引起线程阻塞的方法。
13、线程阻塞的三种情况
- 等待阻塞 -- 通过调用线程的wait()方法,让线程等待某工作的完成。
- 同步阻塞 -- 线程在获取synchronized同步锁失败(因为锁被其它线程所占用),它会进入同步阻塞状态。
-其他阻塞 -- 通过调用线程的sleep()或join() 或发出了I/O请求时,线程会进入到阻塞状态。当 sleep()状态超时、join()等待线程终止或者超 时、或者I/O处理完毕时,线程重新转入就绪状态。
14、被终止的线程
Terminated (被终止) 线程被终止的原因有二:
➢ 一是run()方法中最后一个语句执行完毕而自然死亡。
➢ 二是因为一个没有捕获的异常终止了run方法而意外死亡。
➢ 可以调用线程的 stop 方 法 杀 死 一 个 线 程(thread.stop();),但是,stop方法已过时, 不要在自己的代码中调用它。
15、多线程调度
-Java 的线程调度采用优先级策略:
➢ 优先级高的先执行,优先级低的后执行;
➢ 多线程系统会自动为每个线程分配一个优先级,缺省时,继承其父类的优先级;
➢ 任务紧急的线程,其优先级较高;
➢ 同优先级的线程按“先进先出”的队列原则;
16、Thread类有三个与线程优先级有关的静态量:
➢ MAX_PRIORITY:最大优先权,值为10;
➢ MIN_PRIORITY:最小优先权,值为1;
➢ 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=0;i<=5;i++) { System.out.println("You are Students!"); try{ sleep(500); } catch(InterruptedException e) { System.out.println("Lefthand error.");} } } } class Righthand extends Thread { public void run() { for(int i=0;i<=5;i++) { System.out.println("I am a Teacher!"); try{ sleep(300); } catch(InterruptedException e) { System.out.println("Righthand error.");} } } } public class ThreadTest { static Lefthand left; static Righthand right; public static void main(String[] args) { left=new Lefthand(); right=new Righthand(); left.start(); right.start(); } } |
class Lefthand implements Runnable{
public void run()
{ for(int i=0;i<=5;i++)
{ System.out.println("You are Students!");
try{ Thread.sleep(500); }
catch(InterruptedException e)
{ System.out.println("Lefthand error.");}
}
}
}
class Righthand implements Runnable {
public void run()
{ for(int i=0;i<=5;i++)
{ System.out.println("I am a Teacher!");
try{ Thread.sleep(300); }
catch(InterruptedException e)
{ System.out.println("Righthand error.");}
}
}
}
public class ThreadTest
{
static Thread left;
static Thread right;
public static void main(String[] args)
{
Runnable lefthand = new Lefthand();
left=new Thread(lefthand);
left.start();
Runnable righthand = new Righthand();
right=new Thread(righthand);
right.start(); }
}
class Lefthand implements Runnable{
public void run()
{ for(int i=0;i<=5;i++)
{ System.out.println("You are Students!");
try{ Thread.sleep(500); }
catch(InterruptedException e)
{ System.out.println("Lefthand error.");}
}
}
}
class Righthand implements Runnable {
public void run()
{ for(int i=0;i<=5;i++)
{ System.out.println("I am a Teacher!");
try{ Thread.sleep(300); }
catch(InterruptedException e)
{ System.out.println("Righthand error.");}
}
}
}
public class ThreadTest
{
static Lefthand left;
static Righthand right;
public static void main(String[] args)
{
Runnable lefthand = new Lefthand();
Thread left=new Thread(lefthand);
left.start();
Runnable righthand = new Righthand();
Thread right=new Thread(righthand);
right.start(); }
}
测试程序2:
l 在Elipse环境下调试教材625页程序14-1、14-2 、14-3,结合程序运行结果理解程序;
l 在Elipse环境下调试教材631页程序14-4,结合程序运行结果理解程序;
l 对比两个程序,理解线程的概念和用途;
l 掌握线程创建的两种技术。
package bounce; import java.awt.geom.*; /**
* 从长方形边缘上移动和弹跳的球
* @version 1.33 2007-05-17
* @author Cay Horstmann
*/
public class Ball
{
private static final int XSIZE = 15;
private static final int YSIZE = 15;
private double x = 0;
private double y = 0;
private double dx = 1;
private double dy = 1; /**
* 将球移动到下一个位置,如果球碰到其中一条边,则反向移动
*/
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);
}
}
package bounce; import java.awt.*;
import java.util.*;
import javax.swing.*; /**
* 画球的部件。
* @version 1.34 2012-01-26
* @author Cay Horstmann
*/
public class BallComponent extends JPanel
{
private static final int DEFAULT_WIDTH = 450;
private static final int DEFAULT_HEIGHT = 350; private java.util.List<Ball> balls = new ArrayList<>(); /**
* 向组件添加一个球。
* 要添加的球
*/
public void add(Ball b)
{
balls.add(b);
} public void paintComponent(Graphics g)
{
super.paintComponent(g); // 擦除背景
Graphics2D g2 = (Graphics2D) g;
for (Ball b : balls)
{
g2.fill(b.getShape());
}
} public Dimension getPreferredSize() { return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT); }
}
package bounce; import java.awt.*;
import java.awt.event.*;
import javax.swing.*; /**
* 显示一个动态弹跳球。
* @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);
});
}
} /**
* 带有球组件和按钮的框架。
*/
class BounceFrame extends JFrame
{
private BallComponent comp;
public static final int STEPS = 1000;
public static final int DELAY = 3; /**
* 使用组件构造框架,以显示弹跳球和开始和关闭按钮
*/
public BounceFrame()
{
setTitle("Bounce");
comp = new BallComponent();
add(comp, BorderLayout.CENTER);
JPanel buttonPanel = new JPanel();
addButton(buttonPanel, "Start", event -> addBall());
addButton(buttonPanel, "Close", event -> System.exit(0));
add(buttonPanel, BorderLayout.SOUTH);
pack();
} /**
* 将按钮添加到容器中。
* @param c容器
* @param 按钮标题
* @param 侦听器按钮的操作侦听器
*/
public void addButton(Container c, String title, ActionListener listener)
{
JButton button = new JButton(title);
c.add(button);
button.addActionListener(listener);
} /**
* 向面板中添加一个弹跳球,使其弹跳1000次。
*/
public void addBall()
{
try
{
Ball ball = new Ball();
comp.add(ball); for (int i = 1; i <= STEPS; i++)
{
ball.move(comp.getBounds());
comp.paint(comp.getGraphics());
Thread.sleep(DELAY);
}
}
catch (InterruptedException e)
{
}
}
}
package bounceThread; import java.awt.geom.*; /**
球从A的边缘上移动和反弹的球矩形
* @version 1.33 2007-05-17
* @author Cay Horstmann
*/
public class Ball
{
private static final int XSIZE = 15;
private static final int YSIZE = 15;
private double x = 0;
private double y = 0;
private double dx = 1;
private double dy = 1; /**
Moves the ball to the next position, reversing direction
if it hits one of the edges
*/
public void move(Rectangle2D bounds)
{
x += dx;
y += dy;
if (x < bounds.getMinX())
{
x = bounds.getMinX();
dx = -dx;
}
if (x + XSIZE >= bounds.getMaxX())
{
x = bounds.getMaxX() - XSIZE;
dx = -dx;
}
if (y < bounds.getMinY())
{
y = bounds.getMinY();
dy = -dy;
}
if (y + YSIZE >= bounds.getMaxY())
{
y = bounds.getMaxY() - YSIZE;
dy = -dy;
}
} /**
获取球在当前位置的形状。
*/
public Ellipse2D getShape()
{
return new Ellipse2D.Double(x, y, XSIZE, YSIZE);
}
}
package bounceThread; import java.awt.*;
import java.util.*;
import javax.swing.*; /**
* 画球的部件。
* @version 1.34 2012-01-26
* @author Cay Horstmann
*/
public class BallComponent extends JComponent
{
private static final int DEFAULT_WIDTH = 450;
private static final int DEFAULT_HEIGHT = 350; private java.util.List<Ball> balls = new ArrayList<>(); /**
* 向面板中添加一个球。
* @param b the ball to add
*/
public void add(Ball b)
{
balls.add(b);
} public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
for (Ball b : balls)
{
g2.fill(b.getShape());
}
} public Dimension getPreferredSize() { return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT); }
}
package bounceThread; import java.awt.*;
import java.awt.event.*; import javax.swing.*; /**
* 显示动画弹跳球。
* @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);
});
}
} /**
*带有面板和按钮的框架。
*/
class BounceFrame extends JFrame
{
private BallComponent comp;
public static final int STEPS = 1000;
public static final int DELAY = 5; /**
* 用显示弹跳球和的组件构造框架启动和关闭按钮
*/
public BounceFrame()
{
comp = new BallComponent();
add(comp, BorderLayout.CENTER);
JPanel buttonPanel = new JPanel();
addButton(buttonPanel, "Start", event -> addBall());
addButton(buttonPanel, "Close", event -> System.exit(0));
add(buttonPanel, BorderLayout.SOUTH);
pack();
} /**
* 将按钮添加到容器中。
* @param c容器
* @param 按钮标题
* @param 侦听器按钮的操作侦听器
*/
public void addButton(Container c, String title, ActionListener listener)
{
JButton button = new JButton(title);
c.add(button);
button.addActionListener(listener);
} /**
*在画布上添加一个弹跳球,并启动一根线使其弹跳
*/
public void addBall()
{
Ball ball = new Ball();
comp.add(ball);
Runnable r = () -> {
try
{
for (int i = 1; i <= STEPS; i++)
{
ball.move(comp.getBounds());
comp.repaint();
Thread.sleep(DELAY);
}
}
catch (InterruptedException e)
{
}
};
Thread t = new Thread(r);
t.start();
}
}
测试程序3:分析以下程序运行结果并理解程序。
class Race extends Thread { public static void main(String args[]) { Race[] runner=new Race[4]; for(int i=0;i<4;i++) runner[i]=new Race( ); for(int i=0;i<4;i++) runner[i].start( ); runner[1].setPriority(MIN_PRIORITY); runner[3].setPriority(MAX_PRIORITY);} public void run( ) { for(int i=0; i<1000000; i++); System.out.println(getName()+"线程的优先级是"+getPriority()+"已计算完毕!"); } } |
class Race extends Thread {
public static void main(String args[]) {
Race[] runner = new Race[4];
for (int i = 0; i < 4; i++)
runner[i] = new Race();
for (int i = 0; i < 4; i++)
runner[i].start();
runner[1].setPriority(MIN_PRIORITY);
runner[3].setPriority(MAX_PRIORITY);
} public void run() {
for (int i = 0; i < 1000000; i++);// 执行空语句,用来延时,也可以换成sleep,sleep会释放CPU,会抛出异常
System.out.println(getName() + "线程的优先级是" + getPriority() + "已计算完毕!");
}
}
测试程序4
l 教材642页程序模拟一个有若干账户的银行,随机地生成在这些账户之间转移钱款的交易。每一个账户有一个线程。在每一笔交易中,会从线程所服务的账户中随机转移一定数目的钱款到另一个随机账户。
l 在Elipse环境下调试教材642页程序14-5、14-6,结合程序运行结果理解程序;
package synch; import java.util.*;
import java.util.concurrent.locks.*; /**
* A bank with a number of bank accounts that uses locks for serializing access.
* @version 1.30 2004-08-01
* @author Cay Horstmann
*/
public class Bank
{
private final double[] accounts;
private Lock bankLock;
private Condition sufficientFunds; /**
* 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);//将指定的 double 值分配给指定 double 型数组的每个元素
bankLock = new ReentrantLock();
sufficientFunds = bankLock.newCondition();//返回绑定到此 Lock 实例的新 Condition 实例
} /**
* 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) throws InterruptedException
{
bankLock.lock();//获取锁
try
{
while (accounts[from] < amount)
sufficientFunds.await();//造成当前线程在接到信号或被中断之前一直处于等待状态
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());
sufficientFunds.signalAll();//唤醒所有等待线程
}
finally
{
bankLock.unlock();//释放锁
}
} /**
* Gets the sum of all account balances.
* @return the total balance
*/
public double getTotalBalance()
{
bankLock.lock();
try
{
double sum = 0; for (double a : accounts)
sum += a; return sum;
}
finally
{
bankLock.unlock();
}
} /**
* Gets the number of accounts in the bank.
* @return the number of accounts
*/
public int size()
{
return accounts.length;
}
} Bank
package synch; /**
* This program shows how multiple threads can safely access a data structure.
* @version 1.31 2015-06-21
* @author Cay Horstmann
*/
public class SynchBankTest
{
public static final int NACCOUNTS = 100;
public static final double INITIAL_BALANCE = 1000;
public static final double MAX_AMOUNT = 1000;
public static final int DELAY = 10; public static void main(String[] args)
{
Bank bank = new Bank(NACCOUNTS, INITIAL_BALANCE);
for (int i = 0; i < NACCOUNTS; i++)
{
int fromAccount = i;
Runnable r = () -> {//用Lambda表达式简化代码
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();
}
}
} SynchBankTest
综合编程练习
编程练习1
1. 设计一个用户信息采集程序,要求如下:
(1) 用户信息输入界面如下图所示:
(2) 用户点击提交按钮时,用户输入信息显示控制台界面;
(3) 用户点击重置按钮后,清空用户已输入信息;
(4) 点击窗口关闭,程序退出。
package 一; import java.awt.EventQueue; import javax.swing.JFrame; public class Mian {
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
DemoJFrame page = new DemoJFrame();
});
}
}
package 一; 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)/ 2, (sSize.height - wSize.height)/ 2);//将组件移到新的位置
}
}
package 一; 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(800, 400);
// 设置可见性
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(700, 45));//设置此组件的首选大小
// 给面板的布局设置为网格布局 一行4列
jPanel.setLayout(new GridLayout(1, 4));
JLabel name = new JLabel("Name:");
name.setSize(100, 50);
fieldname = new JTextField("");
fieldname.setSize(80, 20);
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(700, 50));
// 给面板的布局设置为网格布局 一行4列
jPanel.setLayout(new GridLayout(1, 4));
JLabel name = new JLabel("Address:");
fieldadress = new JTextField();
fieldadress.setPreferredSize(new Dimension(150, 50));
JLabel study = new JLabel("Hobby:");
JPanel selectBox = new JPanel();
selectBox.setBorder(BorderFactory.createTitledBorder(""));
selectBox.setLayout(new GridLayout(3, 1));
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(700, 150));
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(2, 1));
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(700, 150));
FlowLayout flowLayout = new FlowLayout(FlowLayout.CENTER, 50, 10);
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(0);
sing.setSelected(false);
dance.setSelected(false);
draw.setSelected(false);
bg.clearSelection();
}
}
2.创建两个线程,每个线程按顺序输出5次“你好”,每个“你好”要标明来自哪个线程及其顺序号。
class Lefthand extends Thread { public void run() { for(int i=0;i<=4;i++) { System.out.println("1.你好"); try{ sleep(500); } catch(InterruptedException e) { System.out.println("Lefthand error.");} } } } class Righthand extends Thread { public void run() { for(int i=0;i<=4;i++) { System.out.println("2.你好"); try{ sleep(300); } catch(InterruptedException e) { System.out.println("Righthand error.");} } } } public class ThreadTest { static Lefthand left; static Righthand right; public static void main(String[] args) { left=new Lefthand(); right=new Righthand(); left.start(); right.start(); } } ThreadTest
3. 完善实验十五 GUI综合编程练习程序。
三、实验总结:
这一周我们主要学习了与线程有关的知识,学习了线程的创建方法,但在实际操作中还是有一定的难度,在老师和助教学长的帮助下完成了用Runnale方法创建线程的任务,理解了线程的优先级属性及调度方法,学到了终止线程的方法,收获挺多的。
转载于:https://www.cnblogs.com/dhlll/p/10126280.html
狄慧201771010104《面向对象程序设计(java)》第十六周学习总结的更多相关文章
- 201571030332 扎西平措 《面向对象程序设计Java》第八周学习总结
<面向对象程序设计Java>第八周学习总结 项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 https: ...
- 201771010118马昕璐《面向对象程序设计java》第八周学习总结
第一部分:理论知识学习部分 1.接口 在Java程序设计语言中,接口不是类,而是对类的一组需求描述,由常量和一组抽象方法组成.Java为了克服单继承的缺点,Java使用了接口,一个类可以实现一个或多个 ...
- 201771010134杨其菊《面向对象程序设计java》第八周学习总结
第八周学习总结 第一部分:理论知识 一.接口.lambda和内部类: Comparator与comparable接口: 1.comparable接口的方法是compareTo,只有一个参数:comp ...
- 201771010134杨其菊《面向对象程序设计java》第七周学习总结
第七周学习总结 第一部分:理论知识 1.继承是面向对象程序设计(Object Oriented Programming-OOP)中软件重用的关键技术.继承机制使用已经定义的类作为基础建立新的类定义,新 ...
- 201771010128 王玉兰《面象对象程序设计 (Java) 》第六周学习总结
---恢复内容开始--- 第一部分:基础知识总结: 1.继承 A:用已有类来构建新类的一种机制,当定义了一个新类继承一个类时,这个新类就继承了这个类的方法和域以适应新的情况: B:特点:具有层次结构. ...
- 201871010126 王亚涛《面向对象程序设计 JAVA》 第十三周学习总结
内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 https://www.cnblogs.com/nwnu-daizh/p/ ...
- 201777010217-金云馨《面向对象程序设计Java》第八周学习总结
项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 https://www.cnblogs.com/nwnu-daizh/p ...
- 201871010126 王亚涛 《面向对象程序设计 (Java)》第十七周学习总结
内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 https://www.cnblogs.com/nwnu-daizh/p/12 ...
- 马凯军201771010116《面向对象程序设计Java》第八周学习总结
一,理论知识学习部分 6.1.1 接口概念 两种含义:一,Java接口,Java语言中存在的结构,有特定的语法和结构:二,一个类所具有的方法的特征集合,是一种逻辑上的抽象.前者叫做“Java接口”,后 ...
- 周强201771010141《面向对象程序设计Java》第八周学习总结
一.理论知识学习部分 Java为了克服单继承的缺点,Java使用了接口,一个类可以实现一个或多个接口. 接口体中包含常量定义和方法定义,接口中只进行方法的声明,不提供方法的实现. 类似建立类的继承关系 ...
随机推荐
- 数据挖掘-K-近邻算法
数据挖掘-K-近邻算法 目录 数据挖掘-K-近邻算法 1. K-近邻算法概述 1.1 K-近邻算法介绍 1.1.1 KNN算法作用 1.1.2 KNN 算法思想 1.1.3 KNN算法特点 1.2 K ...
- Python:Day05-2
面向对象进阶 在前面的章节我们已经了解了面向对象的入门知识,知道了如何定义类,如何创建对象以及如何给对象发消息.为了能够更好的使用面向对象编程思想进行程序开发,我们还需要对Python中的面向对象编程 ...
- 一个关于HttpClient的轮子
由于本文较长,需要耐住性子阅读,另外本文中涉及到的知识点较多,想要深入学习某知识点可以参考其他博客或官网资料.本文也非源码分析文章,示例中的源码大多是伪代码和剪辑过的代码示例,由于该轮子为公司内部使用 ...
- 家庭版记账本app开发完成
经过这几天关于android的相关学习,对于家庭版记账本app以及开发结束. 实现的功能为:用户的注册.登录.添加支出账单.添加收入账单.显示所有的该用户的账单情况(收入和支出).生产图表(直观的显示 ...
- MySQL学习之路3-MySQL中常用数据类型
MySQL中常用数据类型 字符型 存储字符型数据.例如姓名,地址,电话号码等.使用引号括起来,一般使用单引号. 常用类型: char(255) 定长字符串,最大长度255个字符. varchar(25 ...
- 22.1 Extends 继承的 方法重写、@Override的使用、
/* * 继承中成员方法的特点 * 子类中没有这个方法,调用父类的 * 子类中重写了这个方法,调用子类的 * 方法的重写:在子父类当中,子类的方法和父类的完全一样,子类重写了父类的方法(覆盖),当子类 ...
- AJ学IOS(31)UI之Quartz2D图形上下文栈
AJ分享,必须精品 首先,前面博客说过.qurza2d的上下文中有绘图信息和绘图的属性. 但是他是怎么绘制到上下午中的呢? 我们画图时候一半会用这三个步骤: (1)获取上下文 (2)绘图 (3)渲染 ...
- sublime text3配置html环境
1.安装View in Browser 2.配置快捷键 [1]Preferences—Key Bindings—User. [2]插入代码 [ //ie { "keys": [&q ...
- echarts多个数据添加多个纵坐标
在我们echarts开发中,肯定会遇到一个问题.那就是当有多个数据且数据大小差距太大时,就会出现有些数据小到看不到的情况.所以在遇到这种情况时,我通常的解决办法就是给他多加一个坐标轴. option ...
- 植物大战僵尸的代码如何使用python来实现
前言 文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理. 作者:程序IT圈 PS:如有需要Python学习资料的小伙伴可以加点击下方链 ...