周强201771010141《面向对象与程序设计》

第一部分:理论知识学习部分

  1. 程序是一段静态的代码,它是应用程序执行的蓝本。进程是程序的一次动态执行,它对应了从代码加载、执行至执行完毕的一个完整过程。操作系统为每个进程分配一段独立的内存空间和系统资源,包括:代码数据以及堆栈等资源。每一个进程的内部数据和状态都是完全独立的。多任务操作系统中,进程切换对CPU资源消耗较大。

  2.  多线程是进程执行过程中产生的多条执行线索。线程是比进程执行更小的单位。线程不能独立存在,必须存在于进程中,同一进程的各线程间共享进程空间的数据。每个线程有它自身的产生、存在和消亡的过程,是一个动态的概念。多线程意味着一个程序的多行语句可以看上去几乎在同一时间内同时运行。线程创建、销毁和切换的负荷远小于进程,又称为轻量级进程。

  3. Java实现多线程有两种途径:创建Thread类的子类;在程序中定义实现Runnable接口的类。

  4. 用Thread类的子类创建线程:首先需从Thread类派生出一个子类,在该子类中重写run()方法。然后用创建该子类的对象Lefthand left=new Lefthand(); Righthand right=new Righthand();最后用start()方法启动线程 left.start(); right.start();

  5. 用Thread类的子类创建多线程的关键性操作:定义Thread类的子类并实现用户线程操作,即run()方法的实现。在适当的时候启动线程。由于Java只支持单重继承,用这种方法定义的类不可再继承其他父类。

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

      7.Thread(Runnable r):创建一个新线程,它调用r的run(), r是一个实现了Runnable接口的类的实例。

     8.线程两种创建方法比较:实现Runnable接口的优势:符合OO设计的思想;便于用extends继承其它类。采用继承Thread类方法的优点:代码简单。

    9. 线程的终止:当线程的run方法执行方法体中最后一条语句后,或者出现了在run方法中没有捕获的异常时,线程将终止,让出CPU使用权。调用interrupt()方法也可终止线程。 void interrupt() :向一个线程发送一个中断请求,同时把这个线程的“interrupted”状态置为true。若该线程处于 blocked 状 态,会抛出 InterruptedException。

    10. 测试线程是否被中断的方法:static boolean interrupted() :检测当前线程是否已被中断,并重置状态 “interrupted”值为false。  boolean isInterrupted() :检测当前线程是否已被中断 , 不改变状态 “interrupted”值 利用各线程的状态变换,可以控制各个线程轮流 使用CPU,体现多线程的并行性特征。

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

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

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。

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

    17.下面几种情况下,当前运行线程会放弃CPU:线程调用了yield() 或sleep() 方法;抢先式系统下,有高优先级的线程参与调度;由于当前线程进行I/O访问、外存读写、等待用 户输入等操作导致线程阻塞;或者是为等候一个条件变量,以及线程调用wait() 方法。

  18.守护线程的惟一用途是为其他线程提供服务。例如计时线程。在一个线程启动之前,调用setDaemon方法可将线程转换为守护线程。例如:setDaemon(true);

  19.多线程并发执行中的问题:多个线程相对执行的顺序是不确定的。线程执行顺序的不确定性会产生执行结果的不确定性。在多线程对共享数据操作时常常会产生这种不确定性

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

 21. 在Java中解决多线程同步问题的方法有两种:J ava SE 5.0中引入ReentrantLock类。 在共享内存的类方法前加synchronized修饰符。

  22.有关锁对象和条件对象的关键要点:锁用来保护代码片段,保证任何时刻只能有一个线程执行被保护的代码。锁管理试图进入被保护代码段的线程。锁可拥有一个或多个相关条件对象。每个条件对象管理那些已经进入被保护的代码 段但还不能运行的线程。

  23.synchronized关键字作用: 某个类内方法用synchronized 修饰后,该方法被称为同步方法;只要某个线程正在访问同步方法,其他线程欲要访问同步方法就被阻塞,直至线程从同 步方法返回前唤醒被阻塞线程,其他线程方可能进入同步方法。

  24.在同步方法中使用wait()、notify 和notifyAll()方法:一个线程在使用的同步方法中时,可能根据问题的需要,必须使用wait()方法使本线程等待,暂时让出CPU的使用权,并允许其它线程使用这个同步方法。线程如果用完同步方法,应当执行notifyAll()方 法通知所有由于使用这个同步方法而处于等待的 线程结束等待

 第二部分:实验

实验十六  线程技术 

实验时间 2017-12-8

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=0;i<=5;i++)  5 { System.out.println("You are Students!");  6 try{ sleep(500); }  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=0;i<=5;i++) 16 { System.out.println("I am a Teacher!"); 17 try{ sleep(300); } 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 }
复制代码

利用Runnable接口改造程序修改后

 1 class Lefthand implements Runnable {
 2     public void run() {  3 for (int i = 0; i <= 5; i++) {  4 System.out.println("You are Students!");  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 am a Teacher!"); 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 a = new Thread(left); 31 Runnable right = new Righthand(); 32 Thread b = new Thread(right); 33  a.start(); 34  b.start(); 35  } 36 }
ThreadTest

测试程序2:

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

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

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

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

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

 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 = 15; 14 private static final int YSIZE = 15; 15 private double x = 0; 16 private double y = 0; 17 private double dx = 1; 18 private double dy = 1; 19 20 /** 21  Moves the ball to the next position, reversing direction 22  if it hits one of the edges 23 */ 24 //定义了移动方法 25 public void move(Rectangle2D bounds) 26  { 27 x += dx; 28 y += dy; 29 if (x < bounds.getMinX()) 30  { 31 x = bounds.getMinX(); 32 dx = -dx; 33  } 34 if (x + XSIZE >= bounds.getMaxX()) 35  { 36 x = bounds.getMaxX() - XSIZE; 37 dx = -dx; 38  } 39 if (y < bounds.getMinY()) 40  { 41 y = bounds.getMinY(); 42 dy = -dy; 43  } 44 if (y + YSIZE >= bounds.getMaxY()) 45  { 46 y = bounds.getMaxY() - YSIZE; 47 dy = -dy; 48  } 49  } 50 51 /** 52  Gets the shape of the ball at its current position. 53 */ 54 //定义球外形 55 public Ellipse2D getShape() 56  { 57 return new Ellipse2D.Double(x, y, XSIZE, YSIZE); 58  } 59 } 60 61 Ball
Ball 
package bounce;

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 = 450; private static final int DEFAULT_HEIGHT = 350; 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); // erase background Graphics2D g2 = (Graphics2D) g; for (Ball b : balls) { g2.fill(b.getShape()); } } public Dimension getPreferredSize() { return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT); } } BallComponent
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);//将buttonPanel放入边界管理器的南端 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 //生成按钮对象 58 JButton button = new JButton(title); 59  c.add(button); 60 button.addActionListener(listener);//注册监听器事件 61  } 62 63 /** 64  * Adds a bouncing ball to the panel and makes it bounce 1,000 times. 65 */ 66 public void addBall() 67  { 68 try 69  { 70 Ball ball = new Ball(); 71  comp.add(ball); 72 73 for (int i = 1; i <= STEPS; i++) 74  { 75  ball.move(comp.getBounds()); 76  comp.paint(comp.getGraphics()); 77 Thread.sleep(DELAY);//在两个球显示之间有延迟 78  } 79  } 80 catch (InterruptedException e)//中断异常 81  { 82  } 83  } 84 } 85 86 Bounce
Bounce

 

测试程序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++) runner[i]=new Race( );  5 for(int i=0;i<4;i++) runner[i].start( );  6 runner[1].setPriority(MIN_PRIORITY);  7 runner[3].setPriority(MAX_PRIORITY);}  8 public void run( ) {  9 for(int i=0; i<1000000; i++); 10 System.out.println(getName()+"线程的优先级是"+getPriority()+"已计算完毕!"); 11  } 12 }
复制代码

 

 

测试程序4

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

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

B
复制代码
 1 package unsynch;
 2 
 3 import java.util.*;  4  5 /**  6  * 有许多银行账户的银行  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  * 建设银行 16  * @param n 账号 17  * @param initialBalance 每个账户的初始余额 18 */ 19 public Bank(int n, double initialBalance) 20  { 21 accounts = new double[n]; 22  Arrays.fill(accounts, initialBalance); 23  } 24 25 /** 26  * 把钱从一个账户转到另一个账户 27  * @param from 转账账户从 28  * @param to 转账账户到 29  * @param amount 转让的数额 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  * 获取所有帐户余额的总和 43  * @return 总余额 44 */ 45 public double getTotalBalance() 46  { 47 double sum = 0; 48 49 for (double a : accounts) 50 sum += a; 51 52 return sum; 53  } 54 55 /** 56  * 获取银行中的帐户数量 57  * @return 账号 58 */ 59 public int size() 60  { 61 return accounts.length; 62  } 63 } 64 65 Bank
复制代码
复制代码
 1 package unsynch;
 2 
 3 /**  4  * 此程序显示多个线程访问数据结构时的数据损坏  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 } 41 42 UnsynchBankTest
复制代码

 

综合编程练习

编程练习1

1.设计一个用户信息采集程序,要求如下:(1) 用户信息输入界面如下图所示:

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

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

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

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

 

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

复制代码
 1 package BB;
 2 
 3 
 4 class xian1 extends Thread {  5 public void run()  6  {  7 for(int i=1;i<=5;i++)  8 { System.out.println( i+ "你好"+" 来自线程1");  9 try{ sleep(200); } 10 catch(InterruptedException e)//异常捕获 11 { System.out.println("Lefthand error.");} 12  } 13  } 14  } 15 16 class xian2 extends Thread { 17 public void run() 18  { 19 for(int i=1;i<=5;i++) 20 { System.out.println( i+ "你好"+" 来自线程2"); 21 try{ sleep(200); } 22 catch(InterruptedException e)//异常捕获 23 { System.out.println("Lefthand error.");} 24  } 25  } 26 27  } 28 public class xiancheng 29  { 30 //属性 31 static xian1 xian11; 32 static xian2 xian22; 33 public static void main(String[] args) 34 { xian11=new xian1(); 35 xian22=new xian2(); 36 //用start()方法启动线程 37  xian11.start(); 38  xian22.start(); 39  } 40 }
复制代码

 

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

三、总结

    在bank的实验中while循环产生随机数以及锁的概念也不是很理解。需要再多理解程序,希望老师可以再讲解一下。

猜你喜欢

转载自www.cnblogs.com/qq97/p/10126817.html