C20: Threads - PowerPoint PPT Presentation

1 / 6
About This Presentation
Title:

C20: Threads

Description:

C20: Threads. see also: ThreadedBallWorld, DropTest, Tetris source examples ... but usually only one CPU that switches between tasks ... – PowerPoint PPT presentation

Number of Views:37
Avg rating:3.0/5.0
Slides: 7
Provided by: bern8
Category:
Tags: c20 | tetris | threads

less

Transcript and Presenter's Notes

Title: C20: Threads


1
C20 Threads
  • see also ThreadedBallWorld, DropTest, Tetris
    source examples
  • Not covered advanced stuff like notify/notifyAll

2
Multi-threading
  • Multi-tasking do multiple things in parallel
  • Edit your game
  • Surf the web
  • Listen to mp3s
  • but usually only one CPU that switches between
    tasks
  • Multi-threading similar, but inside a single
    program/process/context
  • ?
  • share data directly, same classes/methods/varia
    bles

3
Creating threads 2 ways
  • Subclassing Class Thread
  • class ThreadedBallWorld extends Runnable
  • Must implement run() method
  • Use start() on a new instance
  • (new BallThread()).start()
  • Implement interface Runnable
  • class ThreadedBallWorld implements Runnable
  • Must implement run() method
  • Start by wrapping inside a Thread instance
  • Thread ballThread new Thread(new BallThread())
  • ballThread.start()
  • Both will stop automatically, once run() finishes

4
Scheduling
  • Can be pre-emptive or cooperative,
  • ?Each Thread should regularly call one of
  • yield()
  • wait()
  • sleep()
  • to give other threads a chance to run as well
  • All event handlers (all listeners) and repaint()
    execute in the same event-handling thread
  • ? methods like actionPerformed() should be
    fast, for more substantial computations they
    should
  • Start a new thread
  • Somehow tell another thread what to do
  • Otherwise screen repainting will suffer!

5
Synchronisation
  • If two (or more) threads access some value
    simultanously, and at least one wants to modify
    the value, things can go wrong
  • a 10
  • Thread1 (a1) read a, (b1) compute a10, (c1)
    write a
  • Thread2 (a2) read a, (b2) compute a10, (c2)
    write a
  • What is the value of a after the following
    sequence
  • a1,b1,a2,b2,c2,c1

6
Synchronized methods
  • public synchronized void increment()
  • a 10
  • Only one thread at a time can execute this method
    on the same instance ? no interleaving possible
    (atomic action) ? no inconsistencies
  • but beware of inefficiencies/deadlocks
Write a Comment
User Comments (0)
About PowerShow.com