Threads - PowerPoint PPT Presentation

1 / 11
About This Presentation
Title:

Threads

Description:

The scheduler selects a runnable thread that is not sleeping or blocked ... Possible conflicts when two or more threads access a single object. Example: ... – PowerPoint PPT presentation

Number of Views:55
Avg rating:3.0/5.0
Slides: 12
Provided by: dlb7
Category:
Tags: threads

less

Transcript and Presenter's Notes

Title: Threads


1
Threads
2
Multiple Processes
  • Sometimes we need multiple processes
  • Examples
  • Browser download different images
  • Animate moving figures
  • Application you write needs to check inventory,
    verify customer status, and confirm credit line

3
What are your options?
  • Write your own code to do each task
  • Likely to be sequential, not concurrent
  • Have a loop that does some of each task, then
    moves on to the next
  • Very tough to allocate time properly
  • Have the JVM allocate time to each task for you

4
Definition thread
  • A program unit that executes independently
  • Not quite like a separate program, in that it can
    share variables and monitor status
  • Will simplify the programmer's task by letting
    the JVM alternate tasks

5
How Threads Work
  • Each task implemented as a thread
  • Each thread must be started
  • Each thread is given a "time slice" by the
    "scheduler"
  • The scheduler selects a runnable thread that is
    not sleeping or blocked

6
Two Approaches for Creating Threads
  • Create a class that extends class Thread
  • Implement the Runnable interface
  • Why do this? (because no multiple inheritance)

7
  • public class MyThread extends Thread
  • public void run()
  • try
  • // code here to for threads actions
  • catch (InterruptedException ie)
  • // code here to clean up

8
  • public class MyThreadTest
  • public static void main(String args)
  • myThread oneThread new MyThread()
  • myThread twoThread new MyThread()
  • oneThread.start() //start begins a thread,
  • twoThread.start() //and not run()

9
  • public void run()
  • try
  • for (int i 1 ilt100 i)
  • System.out.println((new Date())
    "Hello")
  • sleep(1000)
  • catch (InterruptedException ie)
  • // code here to clean up

10
Runnable Interface
  • public class MyThreadClass implements Runnable

11
Other Thread Issues
  • Priorities (can set 1 thru 10)
  • These are closer to recommendations than demands
  • Amount of time allocated to each thread can vary
    from run to run (i.e., are computers
    unpredictable?)
  • Synchronization
  • Possible conflicts when two or more threads
    access a single object
  • Example
  • public synchronized void myMethod(int myInt)
  • Deadlocks (i.e., "deadly embrace")
Write a Comment
User Comments (0)
About PowerShow.com