Beruflich Dokumente
Kultur Dokumente
Threads in Java
(Deitel & Deitel)
OOutline
1- Introduction
1- Class Thread: An Overview of the Thread Methods
1- Thread States: Life Cycle of a Thread
1- Thread Priorities and Thread Scheduling
1- Thread Synchronization
1- Daemon Threads
1- Runnable Interface
1- Thread Groups
Introduction
• Threads of execution
– Each thread is a portion of a program that can execute
concurrently with other threads (multithreading)
• C and C++ are single-threaded
• Gives Java powerful capabilities not found in C and C++
– Example: downloading a video clip
• Instead of having to download the entire clip then play it:
• Download a portion, play that portion, download the next
portion, play that portion... (streaming)
• Ensure that it is done smoothly
– Other example applications of multi-threading?{GUI
application , computer games}
• Portability
– Differences between platforms (e.g., Solaris, Windows, …)
• On Solaris (Linux?)
– A thread runs to completion or until a higher priority thread
becomes ready
– Preemption occurs (processor is given to the higher-priority
thread)
• On Win32 (Windows 9x, NT, XP)
– Threads are timesliced
• Thread given quantum of time to execute
• Processor then switched to any threads of equal
priority(CONTEXT SWITCHING)
– Preemption occurs with higher and equal priority threads
Prentice Hall, Inc. All rights reserved.
5
TERMS RELATED
• Context Switching
• Preemptive switch
• Synchronization
• Messaging
• Thread-related methods
– Constructors
• Thread() - Creates a thread with an auto-numbered name
of format Thread-1, Thread-2...
• Thread( threadName ) - Creates a thread with name
– run
• Does “work” of a thread – What does this mean?
• Can be overridden in subclass of Thread or in Runnable
object (more on interface Runnable elsewhere)
– start
• Launches thread, then returns to caller
• Calls run
• Error to call start twice for same thread
• Born state
– Thread just created
– When start called, enters runnable state
• (Ready state) Runnable state
– Highest-priority ready thread enters running state
• Running state
– System assigns processor to thread (thread begins executing)
– When run completes or terminates, enters dead state
• Dead state
– Thread marked to be removed by system
– Entered when run terminates or throws uncaught exception
Creating a thread
• Extending a “Thread” class
-override run() method
constructor: public Thread(String threadName)
Output
• Child thread: Thread[Demo Thread,5,main]
• Main Thread: 5
• Child Thread: 5
• Child Thread: 4
• Main Thread: 4
• Child Thread: 3
• Child Thread: 2
• Main Thread: 3
• Child Thread: 1
• Exiting child thread.
• Main Thread: 2
• Main Thread: 1
• Main thread exiting.
Output
• Child thread: Thread[Demo Thread, 5 , main]
• Main Thread: 5
• Child Thread: 5
• Child Thread: 4
• Main Thread: 4
• Child Thread: 3
• Child Thread: 2
• Main Thread: 3
• Child Thread: 1
• Exiting child thread.
• Main Thread: 2
• Main Thread: 1
• Main thread exiting.
Runnable Interface
Output
• Child thread: Thread[Demo Thread,5,main]
• Main Thread: 5
• Child Thread: 5
• Child Thread: 4
• Main Thread: 4
• Child Thread: 3
• Child Thread: 2
• Main Thread: 3
• Child Thread: 1
• Exiting child thread.
• Main Thread: 2
• Main Thread: 1
• Main thread exiting.
Thread Synchronization
• Monitors
define?
Java monitor
– Object with synchronized methods
• Any object can be a monitor
– Methods declared synchronized
• public synchronized int myMethod( int x )
• Only one thread can execute a synchronized method at
a time
– Obtaining the lock and locking an object
• If multiple synchronized methods, only one may be active
– Java also has synchronized blocks of code
Thread Synchronization
Synchonized blocks
Interthread communication
• Used to allow synchronized threads to
communicate with each other.
• Methods
Wait()
Notify()
NotifyAll()
Contd..
• Wait()
causes current thread to release the lock and wait
until:
1. the specified time elapsed
2. Another thread calls notify() or notifyAll()
• Notify()
call notify to tell a single waiting thread to
enter ready state
• NotifyAll()
- tells all waiting threads to enter ready state
• Solution
The producer is to either go to sleep or discard data if the buffer is full.
The next time the consumer removes an item from the buffer, it
notifies the producer, who starts to fill the buffer again. In the same
way, the consumer can go to sleep if it finds the buffer to be empty.
The next time the producer puts data into the buffer, it wakes up the
sleeping consumer.
An inadequate solution could result in a deadlock where both
processes are waiting to be awakened.
• {
• int value = 0;
• while (true)
• {
• synchronized (this)
• {
• while (list.size()==capacity)
• wait();//GIVING INTRINSIC LOCK ON PC AND GO ON
WAITING
•
• System.out.println("Producer produced-" + value);
• // to insert the jobs in the list
• list.add(value++);
• // notifies the consumer thread that now it can start consuming
notify();
• Thread.sleep(1000);
• }
• }
• }
Prentice Hall, Inc. All rights reserved.
• // Function called by consumer thread System.out.println("Consumer consumed- 46
”+val);
• public void consume() throws
InterruptedException
• { // Wake up producer thread
• while (true) notify();
• {
• synchronized (this)
// and sleep
• {
• // consumer thread waits while Thread.sleep(1000);
//list is empty }
• while (list.size()==0)
}
• wait();//GIVE INTRINSIC
LOCK ON PC AND NOTIFY }
PRODUCER }
•
}
• //to retrive the ifrst job in the list
• int val = list.removeFirst();
•
•
OUTPUT
Join()