Java Threads 1 - PowerPoint PPT Presentation

1 / 33
About This Presentation
Title:

Java Threads 1

Description:

new SimpleThread('Fiji').start(); } Extend Thread. Thread's starting point ... Fiji. Jamaica. Fiji. Jamaica. Jamaica. Web programming Winter 2006. Thread. void ... – PowerPoint PPT presentation

Number of Views:311
Avg rating:3.0/5.0

less

Transcript and Presenter's Notes

Title: Java Threads 1


1
Java Threads 1
  • Web Programming course
  • Dan Goldwasser
  • dgoldwas_at_cs.haifa.ac.il

2
What are threads?
  • A thread in computer science is short for a
    thread of execution or a sequence of
    instructions. Multiple threads can be executed in
    parallel on many computer systems.
  • This multithreading generally occurs by time
    slicing (where a single processor switches
    between different threads) or by multiprocessing
    (where threads are executed on separate
    processors).
  • Threads are similar to processes, but differ in
    the way that they share resources.
  • (From Wikipedia, the free encyclopedia)

3
Thread operation
Each sort is executed by a different thread
4
Some Buzz words
  • Multithreading vs. Multitasking
  • Concurrency vs. parallelism

5
What is good for?
  • Maintain responsiveness of an application during
    a long running task
  • Enable cancellation of separable tasks
  • Some problems are intrinsically parallel
  • To monitor status of some resource (DB)
  • Some APIs and systems demand it Swing
  • To take advantage of multiple processors

Can you think of one?
6
Java implementation of threads
  • We shall look at three version of thread
    instances
  • Interface Runnable
  • Class TimerTask
  • Class Thread

7
java.lang.Runnable
  • An adapter which enables any given class to
    operate as a thread
  • Requires one method be implemented
  • public void run()
  • Most common method for adding threads to an
    application

8
Example 1
  • class Counter implements Runnable
  • private int maxNumber
  • public Counter(int max)
  • maxNumbermax
  • public void run()
  • int i0
  • while(iltmaxNumber)
  • i

the threads starting point
9
Timer and TimerTask
  • A simple way to use threads is to schedule a
    timer and let the thread work periodically
  • Class Timer
  • Class TimerTask

10
class TimerTask
  • A task that can be scheduled for one-time or
    repeated execution by a Timer.

Methods Booelan cancel() - Cancels this timer
task. abstract  void run() - The action to be
performed by this timer task.  Long
scheduledExecutionTime() - Returns the scheduled
execution time of the most recent actual
execution of this task.
11
class Timer
  • facility for threads to schedule tasks for future
    execution in a background thread.

cancel() Terminates this timer, discarding any
currently scheduled tasks. schedule(TimerTask task
, Date time) Schedules the specified task for
execution at the specified time. schedule(TimerTas
k task, long delay)  Schedules the specified task
for execution after the specified
delay. schedule(TimerTask task, long delay,
long period)   Schedules the specified task for
repeated fixed-delay execution, beginning after
the specified delay. scheduleAtFixedRate(TimerTask
 task, Date firstTime, long period)  Schedules
the specified task for repeated fixed-rate
execution, beginning at the specified time.
12
Example 2
  • public class Reminder
  • Timer timer
  • public Reminder(int seconds)
  • timer new Timer()
  • timer.schedule(new RemindTask(),seconds1000)
  • class RemindTask extends TimerTask
  • public void run()
  • System.out.println("Time's up!")
  • cancel() //Terminate the timer thread
  • public static void main(String args)
  • new Reminder(5)

Create a new timer instance and schedule a
TimerTask for it
Extend TimerTask
13
class Thread
  • A base class with maximum threading
    functionality.
  • While less common, it is far more powerful.
  • Forces the focus of your class to its
    threadedness.
  • Minimum requirements are like Runnable
  • public void run()

14
class Thread
Thread
Runnable
Thread()
Thread(Runnable target)
void run()
void run()
void start()
...
15
Example 3
  • public class SimpleThread extends Thread
  • public SimpleThread(String str)
  • super(str)
  • public void run()
  • for (int i 0 i lt 10 i)
  • System.out.println(i " " getName())
  • System.out.println("DONE! " getName())
  • public static void main (String args)
  • new SimpleThread("Jamaica").start()
  • new SimpleThread("Fiji").start()

Extend Thread
Threads starting point
What is the output of this code?
16
What is the output of this code?
public static void main (String args) new
SimpleThread("Jamaica").start() new
SimpleThread("Fiji").start()
Jamaica Jamaica Jamaica Fiji
Fiji Jamaica Jamaica Fiji
Jamaica Fiji Jamaica Jamaica
?
17
(No Transcript)
18
Example 4
  • class Counter implements Runnable
  • private int maxNumber
  • public Counter(int max)
  • maxNumbermax
  • public void run()
  • int i0
  • while(iltmaxNumber)
  • public static void main(String args)
  • runnable rnew Counter(5)
  • Thread t new Thread(r)
  • t.start()

A Thread instance wraps a runnable implementation
instance
19
Thread life cycle
Why not clockThread.sleep?
Thread.sleep(1000)
clockThread new Thread(this, "Clock")
clockThread.start()
Run method termination
20
Thread states
  • A thread is not runnable if
  • Its sleep method is invoked
  • The thread calls the wait method to wait for a
    specific condition to be satisfied
  • The thread is blocking on I/O
  • A thread will be runnable again when-
  • If a thread has been put to sleep, the specified
    number of milliseconds must elapse
  • If a thread is waiting for a condition, then
    another object must notify the waiting thread of
    a change in condition by calling notify or
    notifyAll
  • If a thread is blocked on I/O, the I/O must
    complete

21
Interrupting a thread
  • If this thread is blocked in an invocation of the
    wait(), wait(long), or wait(long, int) methods of
    the Object class, or of the join(), join(long),
    join(long, int), sleep(long), or sleep(long,
    int), methods of this class, then its interrupt
    status will be cleared and it will receive an
    InterruptedException.
  • If this thread is blocked in an I/O operation
    upon an interruptible channel then the channel
    will be closed, the thread's interrupt status
    will be set, and the thread will receive a
    ClosedByInterruptException.
  • If none of the previous conditions hold then this
    thread's interrupt status will be set

22
Interrupting a thread
  • The program creates two threads and interrupts
    them

public class Interrupting public static
void main (String args) Counter
c new Counter ( ) Sleeper s new
Sleeper ( ) c.start ( )
s.start ( ) try
Thread.sleep (2000)
catch (InterruptedException e)
c.interrupt ( ) s.interrupt (
)
23
  • class Counter extends Thread
  • public void run ( )
  • long count 0
  • while (true)
  • if(Thread.interrupted ( ) )
  • System.out.println
    (Counter was interrupted)
  • System.out.println (count
    count)
  • break
  • count
  • class Sleeper extends Thread
  • public void run ( )
  • try
  • Thread.sleep (5000)
  • catch (InterruptedException e)
  • System.out.println (Sleeper
    was interrupted)

24
Thread Identification
  • The identity of the currently running thread can
    be found using the currentThread method
  • This has a static modifier, which means that
    there is only one method for all instances of
    Thread objects
  • The method can always be called using the Thread
    class

public class Thread extends Object
implements Runnable ... public static
Thread currentThread() ...
When is it useful?
25
Thread Scheduling
  • Execution of multiple threads on a single CPU in
    some order is called scheduling
  • The JRE supports a very simple, deterministic
    scheduling algorithm called fixed-priority
    scheduling.
  • schedules threads on the basis of their priority
    relative to other Runnable threads.
  • The thread scheduling algorithm is also
    preemptive. If at any time a thread with a higher
    priority than all other Runnable threads becomes
    Runnable, system chooses the new higher-priority
    thread for execution.
  • The new thread is said to preempt the other
    threads

26
Thread priorities and scheduling
  • Every thread has a priority which can be
    increased or decreased by calling the
    setPriority() method
  • Thread.MIN_PRIORITY is the minimum priority
    (defined 1)
  • Thread.MAX_PRIORITY is the maximum priority
    (defined as 10)
  • When a thread is created, it is given a priority
    of 5 defined as Thread.NORM_PRIORITY

27
Time slicing
  • Time slicing comes into play when multiple
    Runnable threads of equal priority are the
    highest-priority threads competing for the CPU
  •  The Java platform does not implement time
    slicing. However, some platforms do support time
    slicing. Your programs should not rely on time
    slicing, as it may produce different results on
    different systems
  • A thread can voluntarily yield the CPU by calling
    the yield method. The yield method gives other
    threads of the same priority a chance to run. If
    no equal-priority threads are Runnable, the yield
    is ignored.

28
Thread scheduling
  • Differs depending on the operating system
  • Windows NT
  • Each thread is given a time slice after which it
    is pre-empted by another thread of higher or
    equal priority
  • Solaris (UNIX)
  • A thread can only be pre-empted by a thread of
    higher priority. If one is not available, the
    thread runs to completion
  • In both cases, lower priority threads can only
    run if all higher priority threads are blocked

29
What is the output of this code?
public static void main (String args) new
SimpleThread("Jamaica").start() new
SimpleThread("Fiji").start()
Jamaica Jamaica Jamaica Fiji
Fiji Jamaica Jamaica Fiji
Jamaica Fiji Jamaica Jamaica
?
30
Hmmm
  • Scheduling multithreaded programs introduces some
    new concepts
  • non-determinism
  • race condition
  • concurrency
  • A mechanism for synchronizing the threads could
    be useful.. (next session)

31
Summary
  • What are threads? What are they good for?
  • How are threads implemented in Java?
  • In what states could a thread be? How does a
    thread move between states?
  • How is the threads execution order determined?
  • What are the risks of using threads?

32
  • Questions?

33
Example 3
  • public class SimpleThread extends Thread
  • public SimpleThread(String str)
  • super(str)
  • public void run()
  • for (int i 0 i lt 10 i)
  • System.out.println(i " " getName())
  • System.out.println("DONE! " getName())
  • public static void main (String args)
  • new SimpleThread("Jamaica").start()
  • new SimpleThread("Fiji").start()

Extend Thread
Threads starting point
What is the output of this code?
Write a Comment
User Comments (0)
About PowerShow.com