实验十六  线程技术

实验时间 2017-12-8

1、实验目的与要求

(1) 掌握线程概念;

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

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

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

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

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

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

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

  Java 提供一个 线程调度器 来监控程序启动后进入 来监控程序启动后进入 来监控程序启动后进入 来监控程序启动后进入 来监控程序启动后进入 来监控程序启动后进入 来监控程序启动后进入 来监控程序启动后进入              监控程序启动后进入 来监控程序启动后进入 可运行状态的 所有线程。调度器按照可运行状态的 所有线程。调度器按照可运行状态的 所有线程。调度器按照可运行状态的 所有线程。调度器按照优先级决定应调       度 哪些线程来执行。 优先级决定应调度哪些线程来执行。
– 处于可运行状态的线程首先进入 就绪队 列排就绪队 列排就绪队 列排就绪队 列排就绪队 列排就绪队 列排等 候处理器资源,同一时刻在就绪队列中的线程可 候处理器资源,同一时刻在就绪队列中的线程可 候处理器资源,同一时刻在就绪队列中的线程可 候处理器资源,同一时刻在就绪队列中的线程可 能有多个。 Java 的多线程系统会给每个自动 的多线程系统会给每个自动 的多线程系统会给每个自动 的多线程系统会给每个自动 的多线程系统会给每个自动 的多线程系统会给每个自动 的多线程系统会给每个自动 的多线程系统会给每个自动 的多线程系统会给每个自动 的多线程系统会给每个自动 的多线程系统会给每个自动 的多线程系统会给每个自动 的多线程系统会给每个自动 的多线程系统会给每个自动 分配一个线程的优先级。

Java 的线程调度采用优先级策略 :
 优先级高的执行,低后;
 多线程系统会自动为每个分配一优先级,缺省时,继承其父类的优先级;
 任务紧急的线程,其优先级较高;
 同优先级的线程按“进出”队列原则;
多线程调度

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

多线程并发运行不确定性问题解决方案: 多线程并发运行不确定性问题解决方案: 多线程并发运行不确定性问题解决方案: 多线程并发运行不确定性问题解决方案: 多线程并发运行不确定性问题解决方案: 多线程并发运行不确定性问题解决方案: 多线程并发运行不确定性问题解决方案: 多线程并发运行不确定性问题解决方案: 多线程并发运行不确定性问题解决方案: 多线程并发运行不确定性问题解决方案: 多线程并发运行不确定性问题解决方案: 多线程并发运行不确定性问题解决方案: 多线程并发运行不确定性问题解决方案: 多线程并发运行不确定性问题解决方案: 多线程并发运行不确定性问题解决方案: 多线程并发运行不确定性问题解决方案: 多线程并发运行不确定性问题解决方案: 多线程并发运行不确定性问题解决方案: 引入线 引入线 引入线 程同步机制 程同步机制 程同步机制 程同步机制 程同步机制 ,使得另一线程要用该方法 使得另一线程要用该方法 使得另一线程要用该方法 使得另一线程要用该方法 使得另一线程要用该方法 使得另一线程要用该方法 使得另一线程要用该方法 使得另一线程要用该方法 使得另一线程要用该方法 使得另一线程要用该方法 使得另一线程要用该方法 使得另一线程要用该方法 ,就只 能等待 。
 在Java 中解决多线程同步问题 的方法有两种: 的方法有两种: 的方法有两种: 的方法有两种: 的方法有两种: 的方法有两种: 的方法有两种:
-Java SE 5.0中引入 ReentrantLock ReentrantLock ReentrantLockReentrantLock ReentrantLock类(P 648648648页)。
-在共享内存的类方法前加 在共享内存的类方法前加 在共享内存的类方法前加 在共享内存的类方法前加 在共享内存的类方法前加 在共享内存的类方法前加 在共享内存的类方法前加 在共享内存的类方法前加 在共享内存的类方法前加 在共享内存的类方法前加 在共享内存的类方法前加 synchronizedsynchronizedsynchronized synchronized synchronized synchronizedsynchronized修饰符 修饰符 修饰符 。

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();

}

}

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

View Code

测试程序2:

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

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

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

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

 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 }

View Code

 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 }

View Code

 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());
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);
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());
75             comp.paint(comp.getGraphics());
76             Thread.sleep(DELAY);
77          }
78       }
79       catch (InterruptedException e)
80       {
81       }
82    }
83 }

View Code

 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    public void move(Rectangle2D bounds)
25    {
26       x += dx;
27       y += dy;
28       if (x < bounds.getMinX())
29       {
30          x = bounds.getMinX();
31          dx = -dx;
32       }
33       if (x + XSIZE >= bounds.getMaxX())
34       {
35          x = bounds.getMaxX() - XSIZE;
36          dx = -dx;
37       }
38       if (y < bounds.getMinY())
39       {
40          y = bounds.getMinY();
41          dy = -dy;
42       }
43       if (y + YSIZE >= bounds.getMaxY())
44       {
45          y = bounds.getMaxY() - YSIZE;
46          dy = -dy;
47       }
48    }
49
50    /**
51       Gets the shape of the ball at its current position.
52    */
53    public Ellipse2D getShape()
54    {
55       return new Ellipse2D.Double(x, y, XSIZE, YSIZE);
56    }
57 }

View Code

 1 package bounceThread;
 2
 3 import java.awt.*;
 4 import java.util.*;
 5 import javax.swing.*;
 6
 7 /**
 8  * The component that draws the balls.
 9  * @version 1.34 2012-01-26
10  * @author Cay Horstmann
11  */
12 public class BallComponent extends JComponent
13 {
14    private static final int DEFAULT_WIDTH = 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 panel.
21     * @param b the ball to add
22     */
23    public void add(Ball b)
24    {
25       balls.add(b);
26    }
27
28    public void paintComponent(Graphics g)
29    {
30       Graphics2D g2 = (Graphics2D) g;
31       for (Ball b : balls)
32       {
33          g2.fill(b.getShape());
34       }
35    }
36
37    public Dimension getPreferredSize() { return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT); }
38 }

View Code

 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    /**
37     * Constructs the frame with the component for showing the bouncing ball and
38     * Start and Close buttons
39     */
40    public BounceFrame()
41    {
42       comp = new BallComponent();
43       add(comp, BorderLayout.CENTER);
44       JPanel buttonPanel = new JPanel();
45       addButton(buttonPanel, "Start", event -> addBall());
46       addButton(buttonPanel, "Close", event -> System.exit(0));
47       add(buttonPanel, BorderLayout.SOUTH);
48       pack();
49    }
50
51    /**
52     * Adds a button to a container.
53     * @param c the container
54     * @param title the button title
55     * @param listener the action listener for the button
56     */
57    public void addButton(Container c, String title, ActionListener listener)
58    {
59       JButton button = new JButton(title);
60       c.add(button);
61       button.addActionListener(listener);
62    }
63
64    /**
65     * Adds a bouncing ball to the canvas and starts a thread to make it bounce
66     */
67    public void addBall()
68    {
69       Ball ball = new Ball();
70       comp.add(ball);
71       Runnable r = () -> {
72          try
73          {
74             for (int i = 1; i <= STEPS; i++)
75             {
76                ball.move(comp.getBounds());
77                comp.repaint();
78                Thread.sleep(DELAY);
79             }
80          }
81          catch (InterruptedException e)
82          {
83          }
84       };
85       Thread t = new Thread(r);
86       t.start();
87    }
88 }

View Code

测试程序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()+"已计算完毕!");

}

}

测试程序4

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

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

 1 package unsynch;
 2
 3 import java.util.*;
 4
 5 /**
 6  * A bank with a number of bank accounts.
 7  * @version 1.30 2004-08-01
 8  * @author Cay Horstmann
 9  */
10 public class Bank
11 {
12    private final double[] accounts;
13
14    /**
15     * Constructs the bank.
16     * @param n the number of accounts
17     * @param initialBalance the initial balance for each account
18     */
19    public Bank(int n, double initialBalance)
20    {
21       accounts = new double[n];
22       Arrays.fill(accounts, initialBalance);
23    }
24
25    /**
26     * Transfers money from one account to another.
27     * @param from the account to transfer from
28     * @param to the account to transfer to
29     * @param amount the amount to transfer
30     */
31    public void transfer(int from, int to, double amount)
32    {
33       if (accounts[from] < amount) return;
34       System.out.print(Thread.currentThread());
35       accounts[from] -= amount;
36       System.out.printf(" %10.2f from %d to %d", amount, from, to);
37       accounts[to] += amount;
38       System.out.printf(" Total Balance: %10.2f%n", getTotalBalance());
39    }
40
41    /**
42     * Gets the sum of all account balances.
43     * @return the total balance
44     */
45    public double getTotalBalance()
46    {
47       double sum = 0;
48
49       for (double a : accounts)
50          sum += a;
51
52       return sum;
53    }
54
55    /**
56     * Gets the number of accounts in the bank.
57     * @return the number of accounts
58     */
59    public int size()
60    {
61       return accounts.length;
62    }
63 }

View Code

 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 }

View Code

综合编程练习

编程练习1

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

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

View Code

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

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

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

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

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

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

View Code

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

练习一:

 1 package project3;
 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 }

View Code

  1 package project3;
  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 = 600;
 23     private static final int DEFAULT_HEIGHT = 300;
 24
 25     public Main() {
 26         studentlist = new ArrayList<>();
 27         Scanner scanner = new Scanner(System.in);
 28         File file = new File("C:\\Users\\ASUS\\Desktop\\身份证号.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, 7));
 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(110, 90, 60, 30);
 77         jButton1.setBounds(110, 90, 60, 30);
 78         jt1.setBounds(110, 90, 60, 30);
 79         jt2.setBounds(110, 90, 60, 30);
 80         jt3.setBounds(110, 90, 60, 30);
 81         jButton2.setBounds(110, 90, 60, 30);
 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("emmm!你可能是:\n" + list);
144                         //System.out.println("可能的人:" + studentlist.get(i));
145                         //jt.setText("可能的人:" + studentlist.get(i));
146                     }
147                 }
148             }
149         });
150         buttonPanel.add(jButton);
151         buttonPanel.add(jButton1);
152         buttonPanel.add(lab);
153         buttonPanel.add(jt1);
154         buttonPanel.add(lab1);
155         buttonPanel.add(jt2);
156         buttonPanel.add(lab2);
157         buttonPanel.add(jt3);
158         buttonPanel.add(jButton2);
159         add(buttonPanel, BorderLayout.SOUTH);
160         setSize(DEFAULT_WITH, DEFAULT_HEIGHT);
161     }
162
163     public static int agenear(int age) {
164         int min = 53, value = 0, k = 0;
165         for (int i = 0; i < studentlist.size(); i++) {
166             value = studentlist.get(i).getage() - age;
167             if (value < 0)
168                 value = -value;
169             if (value < min) {
170                 min = value;
171                 k = i;
172             }
173         }
174         return k;
175     }
176
177 }

View Code

 1 package project3;
 2
 3 import java.awt.*;
 4 import javax.swing.*;
 5
 6 public class ButtonTest {
 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 }

View Code

练习二:

  1 package project4;
  2
  3 import java.awt.*;
  4 import java.awt.event.ActionEvent;
  5 import java.awt.event.ActionListener;
  6 import java.io.BufferedOutputStream;
  7 import java.io.File;
  8 import java.io.FileOutputStream;
  9 import java.io.IOException;
 10 import java.util.ArrayList;
 11
 12 import javax.swing.*;
 13
 14 public class MyExGUI extends JFrame {
 15     ArrayList<String> user_zongti = new ArrayList<String>();
 16     ArrayList<String> user_zonganswer = new ArrayList<String>();
 17     ArrayList<String> user_answer = new ArrayList<String>();
 18     ArrayList<String> true_answer = new ArrayList<String>();
 19     ArrayList<String> jta_timu = new ArrayList<String>();
 20     ArrayList<String> jta_zong = new ArrayList<String>();
 21     ArrayList<Integer> user_fenshu = new ArrayList<Integer>();
 22     JMenuBar jm; // 菜单条组件
 23     JMenu menu;// 菜单
 24     JMenuItem item1, item2;// 菜单项
 25     JMenu build; // 二级菜单
 26     JMenuItem file, project;
 27     TextArea answer_all = new TextArea();
 28     TextField jta = new TextField();
 29     TextField jta_answer = new TextField();
 30     JLabel num_answer = new JLabel();
 31     JLabel answer;
 32     JToolBar jtb;// 工具条
 33     JButton jb1, jb2, jb3, jb4, jb5, jb6, jb7, jb_next;
 34     int answer_count;
 35     int answer_fenshu;
 36
 37     public MyExGUI() {
 38         // 创建菜单
 39         jm = new JMenuBar();
 40
 41         menu = new JMenu("文件(F)");
 42         menu.setMnemonic('f'); // 助记符
 43
 44         build = new JMenu("新建");
 45
 46         file = new JMenuItem("文件");
 47         project = new JMenuItem("答题");
 48         item1 = new JMenuItem("保存(S)");
 49         item2 = new JMenuItem("退出");
 50
 51         answer = new JLabel("第 1 题");
 52
 53         // 添加菜单项至菜单上
 54         build.add(file);
 55         build.add(project);
 56
 57         menu.add(build);
 58         menu.add(item1);
 59         menu.add(item2);
 60         menu.addSeparator();
 61         // 将菜单加入至菜单栏
 62         jm.add(menu);
 63
 64         JPanel contentPanel = new JPanel();
 65         contentPanel.setLayout(null);
 66         JLabel daan = new JLabel("答案");
 67         JLabel dengyu = new JLabel("=");
 68         num_answer = answer;
 69         num_answer.setFont(new Font("宋体", Font.BOLD, 22));
 70         jb_next = new JButton("下一题");
 71         jta.setFont(new Font("宋体", Font.BOLD, 22));
 72         jta_answer.setFont(new Font("宋体", Font.BOLD, 22));
 73         jb_next.setFont(new Font("宋体", Font.BOLD, 22));
 74         daan.setFont(new Font("宋体", Font.BOLD, 22));
 75         dengyu.setFont(new Font("宋体", Font.BOLD, 22));
 76
 77         contentPanel.add(num_answer);
 78         contentPanel.add(daan);
 79         contentPanel.add(dengyu);
 80         contentPanel.add(jta);
 81
 82         contentPanel.add(jta_answer);
 83         contentPanel.add(answer_all);
 84         contentPanel.add(jb_next);
 85
 86         num_answer.setBounds(90, 20, 130, 50);
 87         daan.setBounds(250, 20, 90, 50);
 88         jta.setBounds(50, 70, 150, 30);
 89         dengyu.setBounds(205, 70, 20, 20);
 90         jta_answer.setBounds(230, 70, 100, 30);
 91         jb_next.setBounds(350, 70, 110, 30);
 92         answer_all.setBounds(50, 120, 400, 300);
 93
 94         this.setJMenuBar(jm); // 添加菜单栏,不能设定位置,会自动放在最上部
 95         this.add(contentPanel);
 96
 97         this.setTitle("在线答题系统");
 98         this.setSize(600, 500);
 99         this.setVisible(true);
100         this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
101         item1.addActionListener(new ActionListener() {
102             public void actionPerformed(ActionEvent arg0) {
103                 FileOutputStream outSTr = null;
104                 BufferedOutputStream Buff = null;
105                 boolean flag = true;
106                 File file;
107                 // String test ;
108                 do {
109                     // test = "test"+count;
110
111                     String inputValue = JOptionPane.showInputDialog("Please input file name");
112                     file = new File(inputValue + "test.txt");
113                     if (!file.exists()) {
114                         // 创建文件
115                         try {
116
117                             flag = file.createNewFile();
118
119                         } catch (IOException e) {
120                             e.printStackTrace();
121
122                         }
123                         flag = false;
124                     } else {
125
126                         JOptionPane.showMessageDialog(null, "该文件名已存在,请重新输入", "ERROR", JOptionPane.ERROR_MESSAGE);
127                         flag = true;
128                     }
129                 } while (flag);
130                 // 写入文件
131                 String u_answer;
132                 try {
133                     outSTr = new FileOutputStream(file);
134                     Buff = new BufferedOutputStream(outSTr);
135                     System.out.println("选择是后执行的代码" + user_zongti.size() + user_answer.size());
136                     for (int i = 0; i < user_zongti.size(); i++) {
137                         try {
138                             Buff.write(user_zongti.get(i).getBytes());
139                             Buff.write("    ".getBytes());
140                             u_answer = user_answer.get(i);
141                             if (u_answer.equals(""))
142                                 u_answer = "没有作答";
143
144                             Buff.write(u_answer.getBytes());
145                             Buff.write("\r\n".getBytes());
146                         } catch (IOException e) {
147                             e.printStackTrace();
148                             i--;
149                         }
150                     }
151                     Buff.flush();
152                     Buff.close();
153
154                 } catch (IOException e) {
155                     e.printStackTrace();
156                 }
157                 try {
158                     outSTr.close();
159                 } catch (IOException e) {
160                     e.printStackTrace();
161                 }
162                 user_zongti.clear();
163                 user_answer.clear();
164             }
165         });
166
167         project.addActionListener(new ActionListener() {
168             public void actionPerformed(ActionEvent arg0) {
169                 arithmetic art = new arithmetic();
170                 true_answer = art.list_answer;
171                 jta_timu = art.list_timu;
172                 jta_zong = art.list;
173                 answer_count = 1;
174                 answer_all.setText("");
175                 for (int i = 0; i < art.list_timu.size(); i++) {
176                     user_zongti.add(jta_zong.get(i));
177                     answer_all.append(jta_timu.get(i));
178                     answer_all.append("\r\n");
179                 }
180                 num_answer.setText("第 " + answer_count + " 题");
181                 jta.setText(jta_timu.get(answer_count - 1));
182                 answer_count++;
183
184             }
185         });
186         jb_next.addActionListener(new ActionListener() {
187             public void actionPerformed(ActionEvent arg0) {
188                 String temp;
189                 temp = jta_answer.getText();
190
191                 if (jta.getText().equals("")) {
192                     JOptionPane.showMessageDialog(null, "错误,请导入题库", "错误", JOptionPane.ERROR_MESSAGE);
193                     return;
194                 }
195                 jta_answer.setText("");
196                 if (answer_count <= 10) {
197                     if (isInteger(temp)) {
198
199                         user_answer.add(temp);
200                         System.out.println("选择否后执行的代码" + temp + "user_size" + user_answer.size());
201                         num_answer.setText("第 " + answer_count + " 题");
202                         jta.setText(jta_timu.get(answer_count - 1));
203                         answer_count++;
204                     } else {
205                         JOptionPane.showMessageDialog(null, "错误", "请输入数字", JOptionPane.ERROR_MESSAGE);
206                     }
207                 } else {
208                     user_answer.add(temp);
209                     System.out.println("选择否后执行的代码" + temp + "user_size" + user_answer.size());
210                     answer_fenshu = 0;
211                     for (int i = 0; i < user_answer.size(); i++) {
212                         if (user_answer.get(i).equals(true_answer.get(i)))
213                             answer_fenshu += 5;
214                     }
215                     user_fenshu.add(answer_fenshu);
216                     Object[] options = { "是", "取消" };
217                     int res = JOptionPane.showOptionDialog(null, "是否查看成绩", "答题完毕", JOptionPane.DEFAULT_OPTION,
218                             JOptionPane.YES_NO_OPTION, null, options, options[0]);
219                     if (res == JOptionPane.YES_OPTION) {
220                         chart ct = new chart(user_fenshu);
221                         ct.setVisible(true);
222
223                     } else {
224                         Object[] option = { "是", "取消" };
225                         int res1 = JOptionPane.showOptionDialog(null, "是否退出程序", "终止框", JOptionPane.DEFAULT_OPTION,
226                                 JOptionPane.YES_NO_OPTION, null, option, option[0]);
227
228                         if (res1 == JOptionPane.YES_OPTION) {
229                             dispose();
230                             System.exit(0);
231
232                         } else {
233
234                         }
235
236                     }
237
238                 }
239
240             }
241         });
242
243         item2.addActionListener(new ActionListener() {
244             public void actionPerformed(ActionEvent e) {
245                 dispose();
246                 System.exit(0);
247             }
248         });
249
250     }
251
252     public static boolean isInteger(String str) {
253         for (int i = str.length(); --i >= 0;) {
254             if (!Character.isDigit(str.charAt(i))) {
255                 return false;
256             }
257         }
258         return true;
259     }
260
261 }

View Code

 1 package project4;
 2
 3 public class Main {
 4
 5     public static void main(String[] args) {
 6         MyExGUI lg = new MyExGUI();
 7         //new MyExGUI();
 8
 9     }
10
11 }

View Code

  1 package project4;
  2
  3 import java.io.BufferedOutputStream;
  4 import java.io.File;
  5 import java.io.FileOutputStream;
  6 import java.io.IOException;
  7 import java.util.ArrayList;
  8 import java.util.Random;
  9 import java.util.Scanner;
 10
 11 public class arithmetic {
 12     ArrayList<String> list = new ArrayList<String>();
 13     ArrayList<String> list_timu = new ArrayList<String>();
 14     ArrayList<String> list_answer = new ArrayList<String>();
 15
 16     public arithmetic() {
 17         FileOutputStream outSTr = null;
 18         BufferedOutputStream Buff = null;
 19         int number_n = 10, count;
 20
 21         ArrayList<String> list_temp = new ArrayList<String>();
 22         String[] operator = new String[] { "+", "-", "*", "/" };
 23
 24         Random rand = new Random();
 25         File file1 = new File("test.txt");
 26         if (file1.exists()) {
 27             // 创建文件
 28             try {
 29                 file1.createNewFile();
 30             } catch (IOException e) {
 31                 e.printStackTrace();
 32             }
 33         }
 34
 35         while (number_n > 0) {
 36             int[] number_temp = new int[rand.nextInt(2) + 3];
 37             String[] str_temp = new String[number_temp.length - 1];
 38             for (int i = 0; i < number_temp.length; i++) {
 39                 if (i < number_temp.length - 1) {
 40                     number_temp[i] = rand.nextInt(100);
 41                     list_temp.add(String.valueOf(number_temp[i]));
 42                     str_temp[i] = operator[rand.nextInt(4)];
 43                     list_temp.add(str_temp[i]);
 44
 45                 }
 46
 47                 else {
 48                     number_temp[i] = rand.nextInt(100);
 49                     list_temp.add(String.valueOf(number_temp[i]));
 50                 }
 51             }
 52
 53             count = calculate_RPN(produce_RPN(list_temp));
 54             if (count != -1) {
 55                 list_timu.add(transform_string(list_temp));
 56                 list_answer.add(String.valueOf(count));
 57                 list_temp.add(" = " + count);
 58                 list.add(transform_string(list_temp));
 59                 number_n--;
 60                 list_temp.clear();
 61             } else
 62                 list_temp.clear();
 63             System.out.println(number_n);
 64
 65         }
 66         try {
 67             outSTr = new FileOutputStream(file1);
 68             Buff = new BufferedOutputStream(outSTr);
 69             for (int i = 0; i < list.size(); i++) {
 70                 try {
 71                     Buff.write(list.get(i).getBytes());
 72                     Buff.write("\r\n".getBytes());
 73                 } catch (IOException e) {
 74                     e.printStackTrace();
 75                     i--;
 76                 }
 77             }
 78             Buff.flush();
 79             Buff.close();
 80
 81         } catch (IOException e) {
 82             e.printStackTrace();
 83         }
 84         // Buff.close();
 85         try {
 86             outSTr.close();
 87         } catch (IOException e) {
 88             e.printStackTrace();
 89         }
 90
 91         for (int i = 0; i < list.size(); i++) {
 92             System.out.print(list.get(i));
 93             System.out.println();
 94         }
 95         System.out.print("计算完毕!");
 96
 97     }
 98
 99     public static int calculate_RPN(ArrayList<String> list_temp) {
100         int i = 0, t;
101         double a = 0, b = 0;
102         String l_temp;
103         Stack sk = new Stack(10);
104         for (t = 0; t < list_temp.size(); t++) {
105             l_temp = list_temp.get(i++);
106             if (!isInteger(l_temp)) {
107                 b = sk.mypop();
108                 a = sk.mypop();
109                 switch (l_temp) {
110                 case "+":
111                     sk.mypush(a + b);
112                     break;
113                 case "-":
114                     if(!(a<b)) {
115                     sk.mypush(a - b);
116                     }
117                     else
118                         return -1;
119                     break;
120                 case "*":
121                     sk.mypush(a * b);
122                     break;
123                 case "/":
124                     if (b == 0||a<b)
125                         return -1;
126                     sk.mypush(a / b);
127                     break;
128                 }
129                 System.out.println("st.mytop: " + sk.mypeek());
130             } else {
131                 sk.mypush((double) Integer.parseInt(l_temp));
132             }
133
134         }
135         if (!sk.myisempty()) {
136             a = sk.mypop();
137             b = a - (int) a;
138             System.out.println("a:  " + a);
139             if (a > 0 && b == 0) {
140                 return (int) a;
141             } else
142                 return -1;
143         } else
144             return -1;
145
146     }
147
148     public static ArrayList<String> produce_RPN(ArrayList<String> list_temp) {
149         int t = 0, i = 0;
150         String tmp;
151         Tack mytack = new Tack(10);
152         ArrayList<String> lt_temp = new ArrayList<String>();
153         while (true) {
154             tmp = list_temp.get(i++);
155             if (isInteger(tmp)) {
156                 lt_temp.add(tmp);
157             } else {
158                 if (mytack.myisempty()) {
159                     mytack.mypush(tmp);
160                 }
161
162                 else {
163                     if (isCPriority(tmp, mytack.mypeek()))
164                         mytack.mypush(tmp);
165                     else {
166                         lt_temp.add(mytack.mypop());
167                         mytack.mypush(tmp);
168                     }
169
170                 }
171             }
172             if (i >= list_temp.size()) {
173                 while (!mytack.myisempty())
174                     lt_temp.add(mytack.mypop());
175                 System.out.println(transform_string(list_temp));
176                 list_temp = lt_temp;
177                 System.out.println(list_temp);
178                 return list_temp;
179             }
180         }
181
182     }
183
184     public static boolean isInteger(String str) {
185         for (int i = str.length(); --i >= 0;) {
186             if (!Character.isDigit(str.charAt(i))) {
187                 return false;
188             }
189         }
190         return true;
191     }
192
193     public static boolean isCPriority(String str, String s) {
194         if ((str + s).equals("*+") || (str + s).equals("*-") || (str + s).equals("/+") || (str + s).equals("/-"))
195             return true;
196         else
197             return false;
198     }
199
200     public static String transform_string(ArrayList<String> list_temp) {
201         String s = "";
202         for (int i = 0; i < list_temp.size(); i++) {
203             s += list_temp.get(i);
204         }
205         return s;
206
207     }
208
209     static class Stack {
210         int mytop;
211         double stk[];
212
213         public Stack(int num) {
214             mytop = -1;
215             stk = new double[num];
216         }
217
218         /* 出栈 */
219         double mypop() {
220             double peek = stk[mytop];
221             mytop--;
222             return peek;
223         }
224
225         /* 入栈 */
226         void mypush(double x) {
227             mytop++;
228             stk[mytop] = x;
229
230         }
231
232         /* 判空 */
233         Boolean myisempty() {
234             if (mytop == -1)
235                 return true;
236             else
237                 return false;
238         }
239
240         /* 取栈顶元素 */
241         double mypeek() {
242             double peek = stk[mytop];
243             return peek;
244         }
245
246         /* 栈大小 */
247         int mysize() {
248             return mytop + 1;
249         }
250     }
251
252     static class Tack {
253         int mytop;
254         String tk[];
255
256         public Tack(int num) {
257             mytop = -1;
258             tk = new String[num];
259         }
260
261         /* 出栈 */
262         String mypop() {
263             String peek = tk[mytop];
264             mytop--;
265             return peek;
266         }
267
268         /* 入栈 */
269         void mypush(String x) {
270             mytop++;
271             tk[mytop] = x;
272
273         }
274
275         /* 判空 */
276         Boolean myisempty() {
277             if (mytop == -1)
278                 return true;
279             else
280                 return false;
281         }
282
283         /* 取栈顶元素 */
284         String mypeek() {
285             String peek = tk[mytop];
286             return peek;
287         }
288
289         /* 栈大小 */
290         int mysize() {
291             return mytop + 1;
292         }
293
294     }
295 }

View Code

实验总结:
通过这一周的学习,掌握了线程的概念,线程创建的两种技术,以及多线程运行的原理,理解和掌握了线程的优先级属性及调度方法,线程同步的概念及实现技术。

在编程中布局方面的问题较为困难,展现出来的界面看起来不是很美观,对布局的内容还有待进一步的理解。

转载于:https://www.cnblogs.com/wy201771010126/p/10125839.html

201771010126 王燕《面向对象程序设计(Java)》第十六周学习总结相关推荐

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

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

  2. 20177101010101 白玛次仁《面向对象程序设计》第十八周学习总结

    实验十八  总复习 实验时间 2018-12-30 1.实验目的与要求 (1) 综合掌握java基本程序结构: (2) 综合掌握java面向对象程序设计特点: (3) 综合掌握java GUI 程序设 ...

  3. 达拉草201771010105《面向对象程序设计(java)》第十六周学习总结

    达拉草201771010105<面向对象程序设计(java)>第十六周学习总结 第一部分:理论知识 1.程序与进程的概念: (1)程序是一段静态的代码,它是应用程序执行的蓝 本. (2)进 ...

  4. 杨玲 201771010133《面向对象程序设计(java)》第十六周学习总结

    <面向对象程序设计(java)>第十六周学习总结 第一部分:理论知识学习部分 1.程序是一段静态的代码,它是应用程序执行的蓝本.进程是程序的一次动态执行,它对应了从代码加载.执行至执行完毕 ...

  5. 面向对象程序设计——Java语言 第3周编程题 查找里程(10分)

    面向对象程序设计--Java语言 第3周编程题 查找里程(10分) 题目内容 下图为国内主要城市之间的公路里程: 你的程序要读入这样的一张表,然后,根据输入的两个城市的名称,给出这两个城市之间的里程. ...

  6. 第十六周学习周报(20180618-20180624)

    第十六周学习周报 一.本周学习情况 1.本周主要学习李宏毅老师的机器学习课程 Unsupervised Learning-Linear Methods Unsupervised Learning-Ne ...

  7. 201771010101 白玛次仁 《2018面向对象程序设计(Java)》第十六周学习总结

    实验十六  线程技术 实验时间 2017-12-8 1.学习总结: 1.程序 是一段静态的代码,它应用程序执行蓝 是一段静态的代码,它应用程序执行蓝 本. 2.进程 是程序的一次动态执行,它对应了从代 ...

  8. 2017面向对象程序设计(Java)第六周学习总结

    转眼间,2017年的法定节日已经休完,我们的java学习也已经进行了六周.下面,我将对上个礼拜的学习情况进行总结. 首先,是学习态度问题.虽然同学们已经从家或者各个旅游景点回来,但是心还是没回来.有同 ...

  9. 201771010109焦旭超《面向对象程序设计(java)》第十六周学习总结

    1.实验目的与要求 (1) 掌握线程概念: (2) 掌握线程创建的两种技术: (3) 理解和掌握线程的优先级属性及调度方法: (4) 掌握线程同步的概念及实现技术: 2.实验内容和步骤 实验1:测试程 ...

最新文章

  1. 2021年广东省高考英语听说成绩查询,广东2021年高考准考证今起自行打印 成绩及分数线6月24日左右公布...
  2. GIt代码托管、Github Desktop和 Pycharm中代码的管理
  3. 在.Net中进行跨线程的控件操作(上篇:Control.Invoke)
  4. java jpa @joincolumn 字段不为空_拥抱开源从表设计到 JPA 实现
  5. TCP/IP 中的二进制反码求和算法
  6. iOS app 企业内部发布及HTTPS服务器配置
  7. matlab eps是什么
  8. 如何优雅的开启mac远程控制
  9. NWT失败反省:不想办法开展业务,天天想着让别人不能用
  10. sas最新sid及安装方法
  11. android 第三方圆弧进度条,Android 圆弧进度条 水平进度条 水波进度条
  12. SoapUI被动接口的压力测试/性能测试
  13. 最新CCC认证目录范围(2019)
  14. C/C++语言开发环境,【5款免费编程器】请查收!
  15. Python 调用摄像头进行人脸识别
  16. 【算法学习】1.渐进复杂性
  17. wyAPP苹果APP 营销
  18. git pull常见操作
  19. openCV+Python实战练习——银行卡号识别
  20. 如何测试WizFi210的”串口转无线”功能?

热门文章

  1. cpu核心数的线程数
  2. python-install-package-C++编译器问题---03
  3. [译] 虚拟现实是如何改变用户体验的:从原型到设备的设计
  4. Git手册 - 分支远程同步
  5. 12C 对表分区维护的增强
  6. java的volatile是什么意思
  7. python语言支持哪些类型的运算符_Python运算符有哪些类型?Python学习
  8. 配置MySQL8.0 环境变量
  9. Sentinel隔离和降级
  10. Spring IoC容器管理的Bean能够被垃圾回收吗?