Download presentation
Presentation is loading. Please wait.
1
Java Threads Part II
2
Lecture Objectives To understand the concepts of multithreading in Java To be able to develop simple multithreaded applications in Java
3
The Runnable Interface Another way to create a thread is to have a class implement the Runnable interface The Runnable interface has one method heading: public void run(); A class that implements Runnable must still be run from an instance of Thread This is usually done by passing the Runnable object as an argument to the thread constructor
4
The Runnable Interface: An Outline public class ClassToRun extends SomeClass implements Runnable {... public void run() { // Fill this as if ClassToRun // were derived from Thread }... public void startThread() { Thread theThread = new Thread(this); theThread.run(); }... }
5
The Runnable Interface: An Example
6
The Runnable Interface: An Example (Cont’d)
10
1.import javax.swing.*; 2.public class TimeThread extends JFrame implements Runnable { 3. 4. private JTextField sec, min, hrs; 5. private JPanel panel; 6. private int time = 0; 7. 8. public TimeThread() { 9. super(“Time"); 10. 11. sec = new JTextField(3); sec.setEditable(false); //makes textfield uneditable 12. min = new JTextField(3); min.setEditable(false); 13. hrs = new JTextField(3); hrs.setEditable(false); 14. 15. panel = new JPanel(); 16. 17. panel.add(hrs); panel.add(min); panel.add(sec); 18. 19. getContentPane().add(panel); pack(); setVisible(true); 20. } Example 1
11
1. public void run() 2. { 3. try { 4. while(true) { 5. Thread.sleep(1000); time++; 6. sec.setText(time%60 + ""); //Display seconds 7. min.setText((time – (time/3600)*3600)/60 + ""); //Display minutes 8. hrs.setText(time/3600 + ""); //Display hours 9. } 10. } catch(InterruptedException e) {} 11. } 12. public static void main(String[] args) 13. { 14. TimeThread t = new TimeThread(); 15. Thread mytime = new Thread(t); 16. mytime.start(); 17. } 18.} Example 1- Continued
12
Threads For Animation Threads can also be used to create animations. In the next example we show a program where a thread is used to create an animation of a ball moving vertically. The run() method increments the y coordinate of the ball to be drawn. If the y-coordinate exceeds the height of the window, the ball is reflected back by negating the increment. The complete program appears in the next slide.
13
Example 2 – Thread Animations import java.awt.*; import javax.swing.*; public class UpDown extends JFrame { public UpDown () { setSize(400,500); add(new DrawingArea()); } class DrawingArea extends JPanel implements Runnable { int radius, xc, yc; Thread t; public DrawingArea() { radius = 20; xc = 30; //signifies x location yc = 20; //signifies y location Thread t = new Thread (this); t.start(); }
14
public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.blue); g.fillOval(xc - radius, yc - radius, 2*radius, 2*radius); } public void run(){ int incry=10; int sleepFor = 50; while(true) { yc += incry ; repaint(); if(yc - radius getSize().height) incry = -incry; //reflect the ball back try{ Thread.sleep (sleepFor); }catch(InterruptedException e) {} } // end while } } public static void main(String[] args){ new UpDown().setVisible(true); }} Example 2 – continued
15
Example 3: ‘Salaam Shabab’ Animation 1.import java.awt.*; 2.import java.awt.event.*; 3.import javax.swing.*; 4.class AnimationPanel extends JPanel implements Runnable { 5. private Font myFont; 6. private int increment = 1; 7. public int xSize, ySize, yCoord = 0; 8. int delay; 9. Thread animator; 10. private boolean onOff=true; 11. public AnimationPanel(int delay) { 12. xSize=400; 13. ySize=350; 14. setSize(xSize, ySize); 15. myFont = new Font ("Serif", Font.ITALIC, 30); 16. animator = new Thread(this); 17. animator.start(); 18. } 19. public void setOnOff(boolean onOff) { 20. this.onOff = onOff; 21. }
16
Example 3: ‘Shabab’ Animation (cont’d) 22. public void paintComponent(Graphics g) { 23. super.paintComponent(g); 24. g.setColor(Color.yellow); 25. g.fillRect(0,0,xSize, ySize); 26. g.setColor (Color.red); 27. g.setFont(myFont); 28. if(onOff) { 29. g.drawString ("Salaam ", xSize/2-100, ySize/2 + yCoord); 30. g.drawString ("Shabab!", xSize/2, ySize/2 - yCoord); 31. } 32. } 33. public void run () { 34. while(true){ 35. yCoord = yCoord + increment;//yCoord min is -150 and max 150 36. if((yCoord == (ySize-50)/2 || (yCoord == -(ySize-50)/2))) 37. increment = -increment; // increment by -1 now 38. try{ 39. Thread.sleep(delay); 40. } catch(InterruptedException e){} 41. repaint(); 42. } 43. } 44. }
17
Example 3: ‘Shabab’ Animation (cont’d) 45. public class SalamShababAnimation extends JApplet{ 46. private Button myButton; 47. private boolean onOffButton = true; 48. private AnimationPanel ap; 49. public void init() { //validate parsing the parameter "fps" 50. int delay = Integer.parseInt(getParameter("fps")); 51. delay = (delay<10)? 10 : delay; 52. Container cp = getContentPane(); 53. cp.setLayout(new BorderLayout()); 54. ap = new AnimationPanel(delay); 55. myButton = new Button ("Start/Stop"); 56. myButton.addActionListener(new ActionListener(){ 57. public void actionPerformed(ActionEvent ae){ 58. onOffButton = !onOffButton; 59. ap.setOnOff(onOffButton); 60. }}); 61. cp.add(myButton,BorderLayout.NORTH); 62. cp.add(ap, BorderLayout.CENTER); 63. } 64.}
18
Example 4: Car Race Animation 1.import java.awt.*; 2.import java.awt.event.*; 3.import javax.swing.*; 4.import java.util.*; 5. class DrivingPanel extends JPanel implements Runnable { 6. private int delay; 7. private Thread animator; 8. private Image car; 9. static final int WIDTH = 600; 10. static final int HEIGHT = 200; 11. private int xPosition, speed; 12. private Random random; 13. public DrivingPanel(Image car, int delay) { 14. this.car = car; 15. this.delay = delay; 16. setSize(WIDTH,HEIGHT); 17. xPosition = getWidth(); 18. random = new Random(); 19. speed = random.nextInt(5);//+1; 20. animator = new Thread(this); 21. animator.start(); 22. }
19
Example 4: Car Race Animation (cont’d) 23. public void run() { 24. while (true) { 25. repaint(); 26. speed = random.nextInt(5)+1; 27. xPosition -= speed; 28. if (xPosition < -car.getWidth(this)) 29. xPosition = getWidth(); 30. try { 31. Thread.sleep(delay); 32. } catch (InterruptedException e) { 33. break; 34. } 35. } 36. } 37. public void paintComponent(Graphics g) { 38. super.paintComponent(g); 39. g.setColor(Color.white); 40. g.fillRect(0, 0, getWidth(), getHeight()); 41. g.drawImage(car, xPosition, getHeight()/2, this); 42. } 43.}
20
Example 4: Car Race Animation (cont’d) 44.public class CarRaceAnimation extends JApplet { 45. public void init() { // You should validate parsing the parameter! 46. int delay = Integer.parseInt(getParameter("fps")); 47. delay = (delay<10)? 10: delay; 48. Image car = getImage(getCodeBase(),"car.gif"); 49. DrivingPanel lane1 = new DrivingPanel(car, delay); 50. DrivingPanel lane2 = new DrivingPanel(car, delay); 51. Container cp = getContentPane(); 52. cp.setLayout(new GridLayout(2,1)); 53. cp.add(lane1); 54. cp.add(lane2); 55. } 56.} Download the car image used in the example from here. here You can also obtain the rocket image for the next example.rocket image
21
Example 5: Rocket Launcher 1.import java.applet.*; 2.import java.awt.*; 3.import java.awt.event.*; 4.import javax.swing.*; 5.public class RocketLauncher extends JApplet implements Runnable, ActionListener { 6. private Image rocket; 7. private int x, y, sec=10; 8. private Thread myThread; 9. private Timer timer = new Timer(1000,this); 10. JTextField tf = new JTextField(5); 11. JButton b = new JButton("Start Count Down"); 12. public void init() { 13. rocket = Toolkit.getDefaultToolkit().getImage("rocket.jpg"); 14. x = 50; 15. y = getSize().height-rocket.getHeight(this)-380; 16. myThread = new Thread(this); 17. tf.setText(" "+sec+" "); 18. b.addActionListener(this); 19. }
22
Example 5: Rocket Launcher (cont’d) 20. public void actionPerformed( ActionEvent ae) { 21. if(ae.getSource() == b) 22. timer.start(); 23. if(ae.getSource() == timer) 24. if(--sec>0) 25. tf.setText(" "+sec+" "); 26. else{ 27. timer.stop(); 28. myThread.start(); 29. } 30. } 31. public void run() { 32. while (y-- != -rocket.getHeight(this)) { 33. try { 34. myThread.sleep(10); 35. } catch (InterruptedException e) {} 36. repaint(); 37. } 38. } 39. public void update(Graphics g){ 40. paint(g); 41. }
23
Example 5: Rocket Launcher (cont’d) 42. public void paint(Graphics g) { 43. g.drawImage(rocket,x,y,null); 44. } 45. public static void main(String [] args){ 46. JFrame frame = new JFrame("My Rocket Launch Pad"); 47. frame.setSize(400,750); 48. Container cp = frame.getContentPane(); 49. cp.setLayout(new GridLayout(1,2)); 50. JPanel p = new JPanel(); 51. JPanel p1 = new JPanel(); 52. p.setLayout(new BoxLayout(p,BoxLayout.Y_AXIS)); 53. RocketLauncher applet = new RocketLauncher(); 54. p.add(applet.b); 55. p1.add(applet.tf); 56. p.add(p1); 57. cp.add(p); 58. applet.setBackground(Color.white); 59. cp.add(applet); 60. frame.setVisible(true); 61. applet.init(); 62. } 63.}
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.