Java Threads Part II - PowerPoint PPT Presentation

1 / 23
About This Presentation
Title:

Java Threads Part II

Description:

Example 5: Rocket Launcher (cont'd) public void actionPerformed( ActionEvent ae) ... Example 5: Rocket Launcher (cont'd) public void paint(Graphics g) { g. ... – PowerPoint PPT presentation

Number of Views:188
Avg rating:3.0/5.0
Slides: 24
Provided by: drlahoua
Category:
Tags: java | launcher | part | threads

less

Transcript and Presenter's Notes

Title: Java Threads Part II


1
Java ThreadsPart 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 (Contd)
7
The Runnable Interface An Example (Contd)
8
The Runnable Interface An Example (Contd)
9
The Runnable Interface An Example (Contd)
10
Example 1
  • import javax.swing.
  • public class TimeThread extends JFrame implements
    Runnable
  • private JTextField sec, min, hrs
  • private JPanel panel
  • private int time 0
  • public TimeThread()
  • super(Time")
  • sec new JTextField(3) sec.setEditable(fals
    e) //makes textfield uneditable
  • min new JTextField(3) min.setEditable(fals
    e)
  • hrs new JTextField(3) hrs.setEditable(fals
    e)
  • panel new JPanel()
  • panel.add(hrs) panel.add(min)
    panel.add(sec)

11
Example 1- Continued
  • public void run()
  • try
  • while(true)
  • Thread.sleep(1000) time
  • sec.setText(time60 "") //Display
    seconds
  • min.setText((time (time/3600)3600)/60
    "") //Display minutes
  • hrs.setText(time/3600 "") //Display
    hours
  • catch(InterruptedException e)
  • public static void main(String args)
  • TimeThread t new TimeThread()
  • Thread mytime new Thread(t)
  • mytime.start()

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
Example 2 continued
public void paintComponent(Graphics g)
super.paintComponent(g)
g.setColor(Color.blue) g.fillOval(xc -
radius, yc - radius, 2radius, 2radius)
public void run() int
incry10 int sleepFor 50
while(true) yc incry
repaint() if(yc - radius lt 0 yc
radius gt 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(t
rue)
15
Example 3 Salaam Shabab Animation
  • import java.awt.
  • import java.awt.event.
  • import javax.swing.
  • class AnimationPanel extends JPanel implements
    Runnable
  • private Font myFont
  • private int increment 1
  • public int xSize, ySize, yCoord 0
  • int delay
  • Thread animator
  • private boolean onOfftrue
  • public AnimationPanel(int delay)
  • xSize400
  • ySize350
  • setSize(xSize, ySize)
  • myFont new Font ("Serif",
    Font.ITALIC, 30)
  • animator new Thread(this)
  • animator.start()
  • public void setOnOff(boolean onOff)

16
Example 3 Shabab Animation (contd)
  • public void paintComponent(Graphics g)
  • super.paintComponent(g)
  • g.setColor(Color.yellow)
  • g.fillRect(0,0,xSize, ySize)
  • g.setColor (Color.red)
  • g.setFont(myFont)
  • if(onOff)
  • g.drawString ("Salaam ",
    xSize/2-100, ySize/2 yCoord)
  • g.drawString ("Shabab!", xSize/2,
    ySize/2 - yCoord)
  • public void run ()
  • while(true)
  • yCoord yCoord increment//yCoord
    min is -150 and max 150
  • if((yCoord (ySize-50)/2 (yCoord
    -(ySize-50)/2)))
  • increment -increment //
    increment by -1 now
  • try
  • Thread.sleep(delay)
  • catch(InterruptedException e)

17
Example 3 Shabab Animation (contd)
  • public class SalamShababAnimation extends
    JApplet
  • private Button myButton
  • private boolean onOffButton true
  • private AnimationPanel ap
  • public void init() //validate parsing the
    parameter "fps"
  • int delay Integer.parseInt(getParamete
    r("fps"))
  • delay (delaylt10)? 10 delay
  • Container cp getContentPane()
  • cp.setLayout(new BorderLayout())
  • ap new AnimationPanel(delay)
  • myButton new Button ("Start/Stop")
  • myButton.addActionListener(new
    ActionListener()
  • public void actionPerformed(ActionE
    vent ae)
  • onOffButton !onOffButton
  • ap.setOnOff(onOffButton)
  • )
  • cp.add(myButton,BorderLayout.NORTH)
  • cp.add(ap, BorderLayout.CENTER)

18
Example 4 Car Race Animation
  • import java.awt.
  • import java.awt.event.
  • import javax.swing.
  • import java.util.
  • class DrivingPanel extends JPanel implements
    Runnable
  • private int delay
  • private Thread animator
  • private Image car
  • static final int WIDTH 600
  • static final int HEIGHT 200
  • private int xPosition, speed
  • private Random random
  • public DrivingPanel(Image car, int delay)
  • this.car car
  • this.delay delay
  • setSize(WIDTH,HEIGHT)
  • xPosition getWidth()
  • random new Random()
  • speed random.nextInt(5)//1

19
Example 4 Car Race Animation (contd)
  • public void run()
  • while (true)
  • repaint()
  • speed random.nextInt(5)1
  • xPosition - speed
  • if (xPosition lt -car.getWidth(this))
  • xPosition getWidth()
  • try
  • Thread.sleep(delay)
  • catch (InterruptedException e)
  • break
  • public void paintComponent(Graphics g)
  • super.paintComponent(g)
  • g.setColor(Color.white)
  • g.fillRect(0, 0, getWidth(),
    getHeight())
  • g.drawImage(car, xPosition,
    getHeight()/2, this)

20
Example 4 Car Race Animation (contd)
  • public class CarRaceAnimation extends JApplet
  • public void init() // You should validate
    parsing the parameter!
  • int delay Integer.parseInt(getParameter("f
    ps"))
  • delay (delaylt10)? 10 delay
  • Image car getImage(getCodeBase(),"car.gif"
    )
  • DrivingPanel lane1 new DrivingPanel(car,
    delay)
  • DrivingPanel lane2 new DrivingPanel(car,
    delay)
  • Container cp getContentPane()
  • cp.setLayout(new GridLayout(2,1))
  • cp.add(lane1)
  • cp.add(lane2)
  • Download the car image used in the example
    from here.
  • You can also obtain the rocket image for the
    next example.

21
Example 5 Rocket Launcher
  • import java.applet.
  • import java.awt.
  • import java.awt.event.
  • import javax.swing.
  • public class RocketLauncher extends JApplet
    implements Runnable, ActionListener
  • private Image rocket
  • private int x, y, sec10
  • private Thread myThread
  • private Timer timer new Timer(1000,this)
  • JTextField tf new JTextField(5)
  • JButton b new JButton("Start Count Down")
  • public void init()
  • rocket Toolkit.getDefaultToolkit().getImag
    e("rocket.jpg")
  • x 50
  • y getSize().height-rocket.getHeight(this)-
    380
  • myThread new Thread(this)
  • tf.setText(" "sec" ")
  • b.addActionListener(this)

22
Example 5 Rocket Launcher (contd)
  • public void actionPerformed( ActionEvent ae)
  • if(ae.getSource() b)
  • timer.start()
  • if(ae.getSource() timer)
  • if(--secgt0)
  • tf.setText(" "sec" ")
  • else
  • timer.stop()
  • myThread.start()
  • public void run()
  • while (y-- ! -rocket.getHeight(this))
  • try
  • myThread.sleep(10)
  • catch (InterruptedException e)
  • repaint()

23
Example 5 Rocket Launcher (contd)
  • public void paint(Graphics g)
  • g.drawImage(rocket,x,y,null)
  • public static void main(String args)
  • JFrame frame new JFrame("My Rocket
    Launch Pad")
  • frame.setSize(400,750)
  • Container cp frame.getContentPane()
  • cp.setLayout(new GridLayout(1,2))
  • JPanel p new JPanel()
  • JPanel p1 new JPanel()
  • p.setLayout(new BoxLayout(p,BoxLayout.Y_AXIS
    ))
  • RocketLauncher applet new
    RocketLauncher()
  • p.add(applet.b)
  • p1.add(applet.tf)
  • p.add(p1)
  • cp.add(p)
  • applet.setBackground(Color.white)
  • cp.add(applet)
  • frame.setVisible(true)
Write a Comment
User Comments (0)
About PowerShow.com