201771010109焦旭超《面向对象程序设计(java)》第十六周学习总结
1、實驗目的與要求
(1) 掌握線程概念;
(2) 掌握線程創建的兩種技術;
(3) 理解和掌握線程的優先級屬性及調度方法;
(4) 掌握線程同步的概念及實現技術;
2、實驗內容和步驟
實驗1:測試程序并進行代碼注釋。
測試程序1:
l?在elipse IDE中調試運行ThreadTest,結合程序運行結果理解程序;
l?掌握線程概念;
l?掌握用Thread的擴展類實現線程的方法;
利用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();} } ThreadTest利用Runnable接口改造程序,掌握用Runnable接口創建線程的方法
class Lefthand implements Runnable { public void run(){for(int i=0;i<=5;i++){ System.out.println("You are Students!");try{ Thread.sleep(500);//休眠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);//休眠300毫秒 }catch(InterruptedException e){ System.out.println("Righthand error.");}}}} public class ThreadTest {public static void main(String[] args){ Righthand righthand = new Righthand();//新建一個righthand對象Lefthand lefthand = new Lefthand();//新建一個lefthand對象Thread right = new Thread(righthand);//start方法在Thread類中,新建Thread類 right.start();Thread left=new Thread(lefthand);left.start();} } Runnable接口測試程序2:
l?在Elipse環境下調試教材625頁程序14-1、14-2 、14-3,結合程序運行結果理解程序;
l?在Elipse環境下調試教材631頁程序14-4,結合程序運行結果理解程序;
l?對比兩個程序,理解線程的概念和用途;
l?掌握線程創建的兩種技術。
package bounce;import java.awt.geom.*;/*** A ball that moves and bounces off the edges of a rectangle* @version 1.33 2007-05-17* @author Cay Horstmann*/ public class Ball {private static final int XSIZE = 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;}}/*** Gets the shape of the ball at its current position.*/public Ellipse2D getShape(){return new Ellipse2D.Double(x, y, XSIZE, YSIZE);} } 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 backgroundGraphics2D g2 = (Graphics2D) g;for (Ball b : balls){g2.fill(b.getShape());}}public Dimension getPreferredSize() { return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT); } } BallComponent package bounce;import java.awt.*; import java.awt.event.*; import javax.swing.*;/*** Shows an animated bouncing ball.* @version 1.34 2015-06-21* @author Cay Horstmann*/ public class Bounce {public static void main(String[] args){EventQueue.invokeLater(() -> {JFrame frame = new BounceFrame();frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setVisible(true);});} }/*** The frame with ball component and buttons.*/ class BounceFrame extends JFrame {private BallComponent comp;public static final int STEPS = 1000;public static final int DELAY = 3;/*** Constructs the frame with the component for showing the bouncing ball and* Start and Close buttons*/public BounceFrame(){setTitle("Bounce");comp = new BallComponent();add(comp, BorderLayout.CENTER);JPanel buttonPanel = new JPanel();addButton(buttonPanel, "Start", event -> addBall());addButton(buttonPanel, "Close", event -> System.exit(0));add(buttonPanel, BorderLayout.SOUTH);pack();}/*** Adds a button to a container.* @param c the container* @param title the button title* @param listener the action listener for the button*/public void addButton(Container c, String title, ActionListener listener){JButton button = new JButton(title);c.add(button);button.addActionListener(listener);}/*** Adds a bouncing ball to the panel and makes it bounce 1,000 times.*/public void addBall(){try{Ball ball = new Ball();comp.add(ball);for (int i = 1; i <= STEPS; i++){ball.move(comp.getBounds());comp.paint(comp.getGraphics());Thread.sleep(DELAY);}}catch (InterruptedException e){}} } Bounce package bounceThread;import java.awt.*; import java.awt.event.*;import javax.swing.*;/*** Shows animated bouncing balls.* @version 1.34 2015-06-21* @author Cay Horstmann*/ public class BounceThread {public static void main(String[] args){EventQueue.invokeLater(() -> {JFrame frame = new BounceFrame();frame.setTitle("BounceThread");frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setVisible(true);});} }/*** The frame with panel and buttons.*/ class BounceFrame extends JFrame {private BallComponent comp;public static final int STEPS = 1000;public static final int DELAY = 5;/*** Constructs the frame with the component for showing the bouncing ball and* Start and Close buttons*/public BounceFrame(){comp = new BallComponent();add(comp, BorderLayout.CENTER);JPanel buttonPanel = new JPanel();addButton(buttonPanel, "Start", event -> addBall());addButton(buttonPanel, "Close", event -> System.exit(0));add(buttonPanel, BorderLayout.SOUTH);pack();}/*** Adds a button to a container.* @param c the container* @param title the button title* @param listener the action listener for the button*/public void addButton(Container c, String title, ActionListener listener){JButton button = new JButton(title);c.add(button);button.addActionListener(listener);}/*** Adds a bouncing ball to the canvas and starts a thread to make it bounce*/public void addBall(){Ball ball = new Ball();comp.add(ball);Runnable r = () -> { try{ for (int i = 1; i <= STEPS; i++){ball.move(comp.getBounds());comp.repaint();Thread.sleep(DELAY);}}catch (InterruptedException e){}};Thread t = new Thread(r);t.start();} } BounceThread測試程序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()+"已計算完畢!");} } Race extends Thread測試程序4
l?教材642頁程序模擬一個有若干賬戶的銀行,隨機地生成在這些賬戶之間轉移錢款的交易。每一個賬戶有一個線程。在每一筆交易中,會從線程所服務的賬戶中隨機轉移一定數目的錢款到另一個隨機賬戶。
l?在Elipse環境下調試教材642頁程序14-5、14-6,結合程序運行結果理解程序;
package unsynch;/*** This program shows data corruption when multiple threads access a data structure.* @version 1.31 2015-06-21* @author Cay Horstmann*/ public class UnsynchBankTest {public static final int NACCOUNTS = 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 = () -> {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();}} } UnsynchBankTest package unsynch;import java.util.*;/*** A bank with a number of bank accounts.* @version 1.30 2004-08-01* @author Cay Horstmann*/ public class Bank {private final double[] accounts;/*** Constructs the bank.* @param n the number of accounts* @param initialBalance the initial balance for each account*/public Bank(int n, double initialBalance){accounts = new double[n];Arrays.fill(accounts, initialBalance);}/*** Transfers money from one account to another.* @param from the account to transfer from* @param to the account to transfer to* @param amount the amount to transfer*/public void transfer(int from, int to, double amount){if (accounts[from] < amount) return;System.out.print(Thread.currentThread());accounts[from] -= amount;System.out.printf(" %10.2f from %d to %d", amount, from, to);accounts[to] += amount;System.out.printf(" Total Balance: %10.2f%n", getTotalBalance());}/*** Gets the sum of all account balances.* @return the total balance*/public double getTotalBalance(){double sum = 0;for (double a : accounts)sum += a;return sum;}/*** Gets the number of accounts in the bank.* @return the number of accounts*/public int size(){return accounts.length;} } Bank綜合編程練習
編程練習1
用戶信息輸入界面如下圖所示:
(1)?用戶點擊提交按鈕時,用戶輸入信息顯示控制臺界面;
(2)?用戶點擊重置按鈕后,清空用戶已輸入信息;
(3)?點擊窗口關閉,程序退出。
import java.awt.EventQueue;import javax.swing.JFrame;public class Mian {public static void main(String[] args) {EventQueue.invokeLater(() -> {DemoJFrame page = new DemoJFrame();});} } Mian 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();} } DemoJFrame 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);//將組件移到新的位置 } } WinCenter2.創建兩個線程,每個線程按順序輸出5次“你好”,每個“你好”要標明來自哪個線程及其順序號。
package shiyan2;public class xiancheng {static xian1 xian11;static xian2 xian22; public static void main(String[] args){ xian11=new xian1();xian22=new xian2(); //用start()方法啟動線程 xian11.start();xian22.start();} }class xian1 extends Thread { public void run(){for(int i=1;i<=5;i++){ System.out.println( i+ "你好"+" 來自線程1");try{ sleep(200); }catch(InterruptedException e) //異常{ System.out.println("Lefthand error.");} } } }class xian2 extends Thread {public void run(){for(int i=1;i<=5;i++){ System.out.println( i+ "你好"+" 來自線程2");try{ sleep(200); }catch(InterruptedException e)//異常捕獲{ System.out.println("Lefthand error.");} }}} xiancheng3. 完善實驗十五 GUI綜合編程練習程序。
實驗總結
通過本周的學習我了解了線程的概念,并且了解了線程創建的兩種技術、線程的優先級屬性及調度方法以及終止線程的方法,(1)用Thread類的子類創建線程(2)用Runnable()接口實現線程;理解了線程的優先級屬性及調度方法和線程的七種狀態。但是這些知識掌握還不牢靠,需要課下多加練習。
轉載于:https://www.cnblogs.com/lcjcc/p/10126884.html
總結
以上是生活随笔為你收集整理的201771010109焦旭超《面向对象程序设计(java)》第十六周学习总结的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 里式代换原则
- 下一篇: 【第九课】MriaDB密码重置和慢查询日