杨玲 201771010133《面向对象程序设计(java)》第十六周学习总结
《面向对象程序设计(java)》第十六周学习总结
第一部分:理论知识学习部分
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”值 。
二 实验部分
第二部分:实验部分
实验名称:实验十六 线程技术
1、实验目的与要求
(1) 掌握线程概念;
(2) 掌握线程创建的两种技术;
(3) 理解和掌握线程的优先级属性及调度方法;
(4) 掌握线程同步的概念及实现技术;
2、实验内容和步骤
实验1:测试程序并进行代码注释。
测试程序1:
l 在elipse IDE中调试运行ThreadTest,结合程序运行结果理解程序;
l 掌握线程概念;
l 掌握用Thread的扩展类实现线程的方法;
l 利用Runnable接口改造程序,掌握用Runnable接口创建线程的方法。
class Lefthand extends Thread { public void run() { for(int i=0;i<=5;i++) { System.out.println("You are Students!"); try{ sleep(500); } catch(InterruptedException e) { System.out.println("Lefthand error.");} } } } class Righthand extends Thread { public void run() { for(int i=0;i<=5;i++) { System.out.println("I am a Teacher!"); try{ sleep(300); } catch(InterruptedException e) { System.out.println("Righthand error.");} } } } public class ThreadTest { static Lefthand left; static Righthand right; public static void main(String[] args) { left=new Lefthand(); right=new Righthand(); left.start(); right.start(); } } |
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{ Thread.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{ Thread.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 { Runnable left = new Lefthand(); 29 Runnable right = new Righthand(); 30 Thread left1 = new Thread(left); 31 Thread right1 = new Thread(right); 32 left1.start(); 33 right1.start(); 34 } 35 }
运行结果如下:
测试程序2:
l 在Elipse环境下调试教材625页程序14-1、14-2 、14-3,结合程序运行结果理解程序;
l 在Elipse环境下调试教材631页程序14-4,结合程序运行结果理解程序;
l 对比两个程序,理解线程的概念和用途;
l 掌握线程创建的两种技术。
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 }
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); // 擦除背景 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 }
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 }
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 }
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);//构造一个新线程,用于给定目标的run()方法 86 t.start();//启动这个线程,将引发调用run方法。这个方法将立即返回,并且新线程将并发运行 87 } 88 }
运行结果如下:
测试程序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()+"已计算完毕!"); } } |
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++) 5 runner[i] = new Race(); 6 for (int i = 0; i < 4; i++) 7 runner[i].start(); 8 runner[1].setPriority(MIN_PRIORITY); 9 runner[3].setPriority(MAX_PRIORITY); 10 } 11 12 public void run() { 13 for (int i = 0; i < 1000000; i++);//延时作用----执行空语句(不释放CPU) 14 System.out.println(getName() + "线程的优先级是" + getPriority() + "已计算完毕!"); 15 } 16 }
运行结果如下:
测试程序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 }
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);//构造一个新线程,用于给定目标的run()方法 37 t.start();//启动这个线程,将引发调用run方法。这个方法将立即返回,并且新线程将并发运行 38 } 39 } 40 }
运行结果如下:
综合编程练习
编程练习1
- 设计一个用户信息采集程序,要求如下:
(1) 用户信息输入界面如下图所示:
(2) 用户点击提交按钮时,用户输入信息显示控制台界面;
(3) 用户点击重置按钮后,清空用户已输入信息;
(4) 点击窗口关闭,程序退出。
1 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
1 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 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
运行结果如下:、
2.创建两个线程,每个线程按顺序输出5次“你好”,每个“你好”要标明来自哪个线程及其顺序号。
1 class xian extends Thread { 2 public void run() 3 { 4 for(int i=1;i<=5;i++) 5 { System.out.println( i+ " (1 : 你好)" ); 6 try{ sleep(200); } 7 catch(InterruptedException e)//异常捕获 8 { System.out.println("Lefthand error.");} 9 } 10 } 11 } 12 13 class xian2 extends Thread { 14 public void run() 15 { 16 for(int i=1;i<=5;i++) 17 { System.out.println( i+ " ( 2 : 你好)"); 18 try{ sleep(200); } 19 catch(InterruptedException e)//异常捕获 20 { System.out.println("Lefthand error.");} 21 } 22 } 23 24 } 25 public class xiancheng 26 { 27 //属性 28 static xian1 xian11; 29 static xian2 xian22; 30 public static void main(String[] args) 31 { xian11=new xian1(); 32 xian22=new xian2(); 33 //用start()方法启动线程 34 xian11.start(); 35 xian22.start(); 36 } 37 }
运行结果如下:
3. 完善实验十五 GUI综合编程练习程序。
4. 实验总结:
通过这次实验我掌握线程的概念;掌握了线程创建的两种技术;也理解和掌握了线程的优先级属性及调度方法;还 掌握了线程同步的概念及实现技术,继续加油!