201771010112罗松《面向对象程序设计(java)》第十六周学习总结
1、實(shí)驗(yàn)?zāi)康呐c要求
(1)?掌握線(xiàn)程概念;
(2)?掌握線(xiàn)程創(chuàng)建的兩種技術(shù);
(3)?理解和掌握線(xiàn)程的優(yōu)先級(jí)屬性及調(diào)度方法;
(4)?掌握線(xiàn)程同步的概念及實(shí)現(xiàn)技術(shù);
2、實(shí)驗(yàn)內(nèi)容和步驟
實(shí)驗(yàn)1:測(cè)試程序并進(jìn)行代碼注釋。
測(cè)試程序1:
l?在elipse?IDE中調(diào)試運(yùn)行ThreadTest,結(jié)合程序運(yùn)行結(jié)果理解程序;
l?掌握線(xiàn)程概念;
l?掌握用Thread的擴(kuò)展類(lèi)實(shí)現(xiàn)線(xiàn)程的方法;
l?利用Runnable接口改造程序,掌握用Runnable接口創(chuàng)建線(xiàn)程的方法。
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();} }利用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);} 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 {public static void main(String[] args) {Runnable left = new Lefthand();Thread a = new Thread(left);Runnable right = new Righthand();Thread b = new Thread(right);a.start();b.start();} }ThreadTest測(cè)試程序2:
l?在Elipse環(huán)境下調(diào)試教材625頁(yè)程序14-1、14-2 、14-3,結(jié)合程序運(yùn)行結(jié)果理解程序;
l?在Elipse環(huán)境下調(diào)試教材631頁(yè)程序14-4,結(jié)合程序運(yùn)行結(jié)果理解程序;
l?對(duì)比兩個(gè)程序,理解線(xiàn)程的概念和用途;
l?掌握線(xiàn)程創(chuàng)建的兩種技術(shù)。
(1)?在Elipse環(huán)境下調(diào)試教材625頁(yè)程序14-1、14-2?、14-3,結(jié)合程序運(yùn)行結(jié)果理解程序;
package bounceThread;import java.awt.geom.*;/**A ball that moves and bounces off the edges of a rectangle* @version 1.33 2007-05-17* @author Cay Horstmann */ public class Ball {private static final int XSIZE = 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 directionif it hits one of the edges*///定義了移動(dòng)方法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);} }BallBall 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); } }BallComponentBallComponent 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());//將按鈕放入buttonPaneladdButton(buttonPanel, "Close", event -> System.exit(0));add(buttonPanel, BorderLayout.SOUTH);//將buttonPanel放入邊界管理器的南端 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){//生成按鈕對(duì)象JButton button = new JButton(title);c.add(button);button.addActionListener(listener);//注冊(cè)監(jiān)聽(tīng)器事件 }/*** 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);//在兩個(gè)球顯示之間有延遲 }}catch (InterruptedException e)//中斷異常 {}} }BounceBounce(2)在Elipse環(huán)境下調(diào)試教材631頁(yè)程序14-4,結(jié)合程序運(yùn)行結(jié)果理解程序;
package bounceThread;import java.awt.*; import java.awt.event.*;import javax.swing.*;/*** 顯示動(dòng)畫(huà)彈跳球* @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;/*** 用顯示彈跳球以及開(kāi)始和關(guān)閉按鈕的組件構(gòu)建框架*/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* 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);}/*** 在畫(huà)布上添加一個(gè)彈跳球,并啟動(dòng)一個(gè)線(xiàn)程使其彈跳*/public void addBall() {Ball ball = new Ball();comp.add(ball);Runnable r = () -> {try {for (int i = 1; i <= STEPS; i++) {ball.move(comp.getBounds());//將球移動(dòng)到下一個(gè)位置,如果碰到其中一個(gè)邊緣則反轉(zhuǎn)方向comp.repaint();//重繪此組件。 Thread.sleep(DELAY);//在指定的毫秒數(shù)內(nèi)讓當(dāng)前正在執(zhí)行的線(xiàn)程休眠 }} catch (InterruptedException e) {}};Thread t = new Thread(r);t.start();} }BounceThreadBounceThread?測(cè)試程序3:分析以下程序運(yùn)行結(jié)果并理解程序。
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()+"線(xiàn)程的優(yōu)先級(jí)是"+getPriority()+"已計(jì)算完畢!");} }測(cè)試程序4
l?教材642頁(yè)程序模擬一個(gè)有若干賬戶(hù)的銀行,隨機(jī)地生成在這些賬戶(hù)之間轉(zhuǎn)移錢(qián)款的交易。每一個(gè)賬戶(hù)有一個(gè)線(xiàn)程。在每一筆交易中,會(huì)從線(xiàn)程所服務(wù)的賬戶(hù)中隨機(jī)轉(zhuǎn)移一定數(shù)目的錢(qián)款到另一個(gè)隨機(jī)賬戶(hù)。
在Elipse環(huán)境下調(diào)試教材642頁(yè)程序14-5、14-6,結(jié)合程序運(yùn)行結(jié)果理解程序;
package unsynch;import java.util.*;/*** 有許多銀行賬戶(hù)的銀行* @version 1.30 2004-08-01* @author Cay Horstmann*/ public class Bank {private final double[] accounts;/*** 建設(shè)銀行* @param n 賬號(hào)* @param initialBalance 每個(gè)賬戶(hù)的初始余額*/public Bank(int n, double initialBalance){accounts = new double[n];Arrays.fill(accounts, initialBalance);}/*** 把錢(qián)從一個(gè)賬戶(hù)轉(zhuǎn)到另一個(gè)賬戶(hù)* @param from 轉(zhuǎn)賬賬戶(hù)從* @param to 轉(zhuǎn)賬賬戶(hù)到* @param amount 轉(zhuǎn)讓的數(shù)額*/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());}/*** 獲取所有帳戶(hù)余額的總和* @return 總余額*/public double getTotalBalance(){double sum = 0;for (double a : accounts)sum += a;return sum;}/*** 獲取銀行中的帳戶(hù)數(shù)量* @return 賬號(hào)*/public int size(){return accounts.length;} }Bankank package unsynch;/*** 此程序顯示多個(gè)線(xiàn)程訪(fǎng)問(wèn)數(shù)據(jù)結(jié)構(gòu)時(shí)的數(shù)據(jù)損壞* @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();}} }UnsynchBankTestUnsynchBankTest綜合編程練習(xí)
編程練習(xí)1
1.設(shè)計(jì)一個(gè)用戶(hù)信息采集程序,要求如下:(1)?用戶(hù)信息輸入界面如下圖所示:
?
(1)?用戶(hù)點(diǎn)擊提交按鈕時(shí),用戶(hù)輸入信息顯示控制臺(tái)界面;
(2)?用戶(hù)點(diǎn)擊重置按鈕后,清空用戶(hù)已輸入信息;
(3)?點(diǎn)擊窗口關(guān)閉,程序退出。
package AA;import java.awt.EventQueue;import javax.swing.JFrame;public class Main {public static void main(String[] args) {EventQueue.invokeLater(() -> {DemoJFrame page = new DemoJFrame();});} }MainMain package AA;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);} }WinCenterWinCenter package o;import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.GridLayout;import javax.swing.BorderFactory; import javax.swing.ButtonGroup; 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 Male;private JRadioButton Female;private JCheckBox read;private JCheckBox sing;private JCheckBox dance;public DemoJFrame() {// 設(shè)置窗口大小this.setSize(800, 400);// 設(shè)置可見(jiàn)性this.setVisible(true);// 設(shè)置標(biāo)題this.setTitle("編程練習(xí)一");// 設(shè)置關(guān)閉操作this.setDefaultCloseOperation(EXIT_ON_CLOSE);// 設(shè)置窗口居中WinCenter.center(this);// 創(chuàng)建四個(gè)面板對(duì)象jPanel1 = new JPanel();setJPanel1(jPanel1); jPanel2 = new JPanel();setJPanel2(jPanel2);jPanel3 = new JPanel();setJPanel3(jPanel3);jPanel4 = new JPanel();setJPanel4(jPanel4);// 設(shè)置容器的為流布局FlowLayout flowLayout = new FlowLayout();this.setLayout(flowLayout);// 將四個(gè)面板添加到容器中this.add(jPanel1);this.add(jPanel2);this.add(jPanel3);this.add(jPanel4);}/** 設(shè)置面一*/private void setJPanel1(JPanel jPanel) {// TODO 自動(dòng)生成的方法存根jPanel.setPreferredSize(new Dimension(700, 45));// 給面板的布局設(shè)置為網(wǎng)格布局 一行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("初中");comboBox.addItem("高中");comboBox.addItem("本科");jPanel.add(name);jPanel.add(fieldname);jPanel.add(study);jPanel.add(comboBox);}/** 設(shè)置面板二*/private void setJPanel2(JPanel jPanel) {// TODO 自動(dòng)生成的方法存根jPanel.setPreferredSize(new Dimension(700, 50));// 給面板的布局設(shè)置為網(wǎng)格布局 一行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));read = new JCheckBox("reading");sing = new JCheckBox("singing");dance = new JCheckBox("danceing");selectBox.add(read);selectBox.add(sing);selectBox.add(dance);jPanel.add(name);jPanel.add(fieldadress);jPanel.add(study);jPanel.add(selectBox);}/** 設(shè)置面板三*/private void setJPanel3(JPanel jPanel) {// TODO 自動(dòng)生成的方法存根jPanel.setPreferredSize(new Dimension(700, 150));FlowLayout flowLayout = new FlowLayout(FlowLayout.LEFT);jPanel.setLayout(flowLayout);JLabel sex = new JLabel("性別:");JPanel selectBox = new JPanel();selectBox.setBorder(BorderFactory.createTitledBorder(""));selectBox.setLayout(new GridLayout(2, 1));bg = new ButtonGroup();Male = new JRadioButton("male");Female = new JRadioButton("female");bg.add(Male );bg.add(Female);selectBox.add(Male);selectBox.add(Female);jPanel.add(sex);jPanel.add(selectBox);}/** 設(shè)置面板四*/private void setJPanel4(JPanel jPanel) {// TODO 自動(dòng)生成的方法存根jPanel.setPreferredSize(new Dimension(700, 150));FlowLayout flowLayout = new FlowLayout(FlowLayout.CENTER, 50, 10);jPanel.setLayout(flowLayout);jPanel.setLayout(flowLayout);JButton sublite = new JButton("提交");JButton reset = new JButton("重置");sublite.addActionListener((e) -> valiData());reset.addActionListener((e) -> Reset());jPanel.add(sublite);jPanel.add(reset);}/** 提交數(shù)據(jù)*/private void valiData() {// TODO 自動(dòng)生成的方法存根// 拿到數(shù)據(jù)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 (read.isSelected()) {hobbystring+="reading ";}if (sing.isSelected()) {hobbystring+="singing ";}if (dance.isSelected()) {hobbystring+="dancing ";}System.out.println(address);if (Male.isSelected()) {System.out.println("male");}if (Female.isSelected()) {System.out.println("female");}System.out.println(hobbystring);}/** 重置*/private void Reset() {// TODO 自動(dòng)生成的方法存根fieldadress.setText(null);fieldname.setText(null);comboBox.setSelectedIndex(0);read.setSelected(false);sing.setSelected(false);dance.setSelected(false);bg.clearSelection();} }DemoJFrameDemoJFrame2.創(chuàng)建兩個(gè)線(xiàn)程,每個(gè)線(xiàn)程按順序輸出5次“你好”,每個(gè)“你好”要標(biāo)明來(lái)自哪個(gè)線(xiàn)程及其順序號(hào)。
package BB;class xian1 extends Thread { public void run(){for(int i=1;i<=5;i++){ System.out.println( i+ "你好"+" 來(lái)自線(xiàn)程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+ "你好"+" 來(lái)自線(xiàn)程2");try{ sleep(200); }catch(InterruptedException e)//異常捕獲{ System.out.println("Lefthand error.");} }}}public class xiancheng {//屬性static xian1 xian11;static xian2 xian22;public static void main(String[] args){ xian11=new xian1();xian22=new xian2();//用start()方法啟動(dòng)線(xiàn)程 xian11.start();xian22.start();}}?
?
?3.?完善實(shí)驗(yàn)十五?GUI綜合編程練習(xí)程序。
3.實(shí)驗(yàn)總結(jié):
通過(guò)這次實(shí)驗(yàn),我大致掌握了線(xiàn)程的概念和線(xiàn)程創(chuàng)建的兩種技術(shù),還大致理解和掌握了線(xiàn)程的優(yōu)先級(jí)屬性及調(diào)度方法,但還有很多還有不太理解的地方,我會(huì)在之后的學(xué)習(xí)中慢慢去弄懂,總的來(lái)說(shuō)這周學(xué)習(xí)比起前幾周來(lái)說(shuō)還算順利,希望在之后的學(xué)習(xí)中能學(xué)到更多。
?
轉(zhuǎn)載于:https://www.cnblogs.com/xuezhiqian/p/10126248.html
總結(jié)
以上是生活随笔為你收集整理的201771010112罗松《面向对象程序设计(java)》第十六周学习总结的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 普通话测试哪个软件准确吗,免费普通话测试
- 下一篇: Java、JSP老年公寓管理系统