Beruflich Dokumente
Kultur Dokumente
CSC-210
Object-Oriented Programming
Lecturer
Sameena Javaid
https://sites.google.com/site/sameenajavaidcs
THREADS
Thread
• A thread is a part of execution in a program.
Computer
Playing Music
Other Video Player
Tasks
My Super Browse
Computer Internet
NotePad
Downloading Playing
Files Game
Music Player
Playing Managing
Songs Playlists
Music
Player
Downloading Accessing
Updates Internet
Program starts
thread
Unlock signal Thread
completes task
Await lock
Timed Waiting
Thread – Methods
New Blocked
t.sleep(),
t.start() t.wait()
Run method
ends
Ready t.run() Running Terminated
Thread Priorities
• When multiple threads are running the order of
execution of threads depend on priority given to
thread.
• Priority values ranges from 1 to 10.(default-5).
• setPriority(int priority) – method to set priority.
Multithreading
• When two or more threads are running in a
process simultaneously then it is called
Multithreading.
Multithreading
public class One extends Thread{
Example
public void run()
{
System.out.println("This is first thread");
}
}
Multithreading Example
public class Main extends Thread{
public static void main(String[] args)
{
Thread thread1 = new Thread(new One());
Thread thread2 = new Thread(new Second());
thread1.start();
thread2.start();
}
}
Synchronization
• The process of making only one thread access
the object when two or more threads are
accessing the same object is called
Synchronization.
• Keyword - ‘synchronized’.
Inter-Thread Communication
• The process of communication between multiple threads
is called Inter-thread communication.
Deadlock
Object
• Deadlock is a situation in 1
which a thread has got an waiting
object and waiting for an
object locked by another
thread which is waiting for
Thread2
the object locked by first Thread1
thread.
waiting
Object
2
Deadlock Example
• Player1 has got a bat to play and waiting for a
ball.
• Player2 has got a ball to play and waiting for a
bat.
• Both are waiting for the resource which are
held by the other player. This leads to
deadlock.