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(); } } |
运行结果:
测试程序2:
l 在Elipse环境下调试教材625页程序14-1、14-2 、14-3,结合程序运行结果理解程序;
1 package bounce; 2 3 import java.awt.*; 4 import java.awt.event.*; 5 import javax.swing.*; 6 7 /** 8 * 显示动画弹跳球 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 * 框架与球组件和按钮 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 * 使用组件构造框架以显示弹跳球和“开始”和“关闭”按钮 35 */ 36 public BounceFrame() 37 { 38 setTitle("Bounce"); 39 comp = new BallComponent(); 40 add(comp, BorderLayout.CENTER); 41 JPanel buttonPanel = new JPanel(); 42 addButton(buttonPanel, "Start", event -> addBall()); 43 addButton(buttonPanel, "Close", event -> System.exit(0)); 44 add(buttonPanel, BorderLayout.SOUTH); 45 pack(); 46 } 47 48 /** 49 * 向容器添加按钮 50 * @param c the container 51 * @param title the button title 52 * @param listener the action listener for the button 53 */ 54 public void addButton(Container c, String title, ActionListener listener) 55 { 56 JButton button = new JButton(title); 57 c.add(button); 58 button.addActionListener(listener); 59 } 60 61 /** 62 * 在面板上添加一个弹跳球,使其反弹1,000次 63 */ 64 public void addBall() 65 { 66 try 67 { 68 Ball ball = new Ball(); 69 comp.add(ball); 70 71 for (int i = 1; i <= STEPS; i++) 72 { 73 ball.move(comp.getBounds()); 74 comp.paint(comp.getGraphics()); 75 Thread.sleep(DELAY); 76 } 77 } 78 catch (InterruptedException e) 79 { 80 } 81 } 82 }