Threads and Java
Threads and Java
6-Dec 2010
1
Task, Process – Background
Concurrency
Threads
LifeCycle of Threads
Thread Priorities & Scheduling
Creating and Executing Threads
Running Threads
Sleeping Threads
Thread Trouble
2
An application written – Start to End
You know every step
Know what follows – Software Lifecycle
Manufacturing processes
Would you be doing only one work at any time?
Probably in a class like this..
Mom’s work?
3
• Many activities at the same time
• Early operating system - DOS (disk OS), Windows 3.1, early MAC version, 1 st
gen computers – performed single tasks.
– Once completed you do the next.
– BATCH processing
– Many Applications - Round Robin
4
5
6
7
• Many times, an application package will
contain many associated executables
8
• Your main application is
dependent on another
process or application or
task
• A layered architecture
of application
development
• Waiting for data or
state or event
• You need Concurrent programming
• Flexibility to do things simultaneously
• Your Application is in
waiting state…how long • No need to wait
• Processes create new process.
• Creating new process is heavy
• Need more resources – memory
• How about a process that will not require new
memory or resources allocated. Something
YOU ARE STUCK that can run within the same process
9
10
• No other languages, except ADA, have thread
support
• Portability of Java code
• Need not worry about any overheads of initialization
and managing of resources of each Operating system
(JVM does the remaining part).
11
12
• New
– Beginning of Thread life. Not ready for execution until programs
moves state to runnable
• Runnable
– Task is being executed
– Data dependency on other threads
• Waiting
– just wait for the other thread completion
• Timed Waiting (Sleeping thread)
– wait for either expiration of timer or the other thread completion
• Blocked
– Wait for long time…
• Terminated
– End of life
13
A thread is associated with an instance of a class Thread. Two
basic strategies for concurrent application
14
public class HelloRunnable implements Runnable
{
@Override
public void run()
{
System.out.println("Hello from a thread!");
}
public void run(Strings arg[])
{
}
public static void main(String args[])
{
// just started a thread
(new Thread( new HelloRunnable() ) ).start();
// Create a Runnable instance
HelloRunnable HR1 = new HelloRunnable();
// We need to get a thread for the runnable created
Thread THR1 = new Thread(HR1);
}
}
15
public class HelloThread extends Thread
{ static int j =0;
public void run()
{
System.out.println("Hello from a thread #”+j++
+”!");
}
public static void main(String args[])
{
(new HelloThread() ).start(); Your Output:
HelloThread HT = new HelloThread();
HT.start();
try { Hello from a thread #0!
HT.sleep(3999L); Hello from a thread #1!
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
16
METHOD Name Method Desc Notes
STOP – Why we should not use it
setName(String ThreadName) Assign a Name for Thread Because it is inherently unsafe. Stopping a thread causes
it to unlock all the monitors that it has locked. (The monitors are
unlocked as the ThreadDeath exception propagates up the
getName Retrieve the name of Thread stack.) If any of the objects previously protected by these
monitors were in an inconsistent state, other threads may now
setPriority(int newPriority) Change priority of thread Java range view these objects in an inconsistent state. Such objects are
said to be damaged.
MAX_PRIORITY = 10
When threads operate on damaged objects, arbitrary behavior
MIN_PRIORITY = 1 can result. This behavior may be subtle and difficult to detect, or
it may be pronounced. Unlike other unchecked exceptions,
getPriority() Read current priority
ThreadDeath kills threads silently; thus, the user has no warning
that his program may be corrupted. The corruption can manifest
currentThread() Get current thread reference itself at any time after the actual damage occurs,
even hours or days in the future.
start()
Join()
17
The static method 'sleep(<long> <param1>)‘
Makes the current thread stop execution for an amount of time
The unit of time is milliseconds (ms = 1/1000 of a sec)
18
public class HelloRunnable implements Runnable
{
@Override
public void run()
{
System.out.println("Hello from a thread!");
try { Thread.sleep(1000L); }
catch(InterruptedException e)
{
System.out.println(“Terminated prematurely due to Exception.”);
}
}
public void run(Strings arg[])
{
}
public static void main(String args[])
{
// just started a thread
(new Thread( new HelloRunnable() ) ).start();
// Create a Runnable instance
HelloRunnable HR1 = new HelloRunnable();
// We need to get a thread for the runnable created
Thread THR1 = new Thread(HR1);
}
}
19
Thread One is alive: true
class MyThread implements Runnable { Thread Two is alive: true public class MainClass {
String name; // name of thread Thread Three is alive: true public static void main(String args[]) {
Waiting for threads to finish. MyThread ob1 = new MyThread("One");
Thread t; MyThread ob2 = new MyThread("Two");
One: 5
MyThread ob3 = new MyThread("Three");
MyThread(String threadname) { Three: 5
name = threadname; One: 4 System.out.println("Thread One is alive: " + ob1.t.isAlive());
t = new Thread(this, name); Three: 4 System.out.println("Thread Two is alive: " + ob2.t.isAlive());
System.out.println("New thread: " + t);
One: 3 System.out.println("Thread Three is alive: " + ob3.t.isAlive());
t.start();
}
Three: 3 try {
One: 2 System.out.println("Waiting for threads to finish.");
public void run() { Three: 2 ob1.t.join();
try { One: 1 ob2.t.join();
for (int i = 5; i > 0; i--) { Three: 1 ob3.t.join();
System.out.println(name + ": " + i); } catch (InterruptedException e) {
Thread.sleep(1000);
One exiting. System.out.println("Main thread Interrupted");
} Three exiting. }
} catch (InterruptedException e) { Two: 5
Two: 4
System.out.println(name + " interrupted."); System.out.println("Thread One is alive: " + ob1.t.isAlive());
} Two: 3 System.out.println("Thread Two is alive: " + ob2.t.isAlive());
System.out.println(name + " exiting."); System.out.println("Thread Three is alive: " + ob3.t.isAlive());
}
Two: 2
} Two: 1 System.out.println("Main thread exiting.");
Two exiting. }
Thread One is alive: false }
Thread Two is alive: false
Thread Three is alive: false
Main thread exiting.
20
Many threads share a common object or data
Usually many reads and few writes
Lead to spurious situation
One of the thread is updating and another is reading
Java way
Give the thread an exclusive access to manipulate data - Semaphore
Other threads wait
Monitor – a Java built-in for synchronization
Only one object will be able to lock at one time
Every object has a monitor and a monitor lock
You need a Synchronization block
21
Mutual Exclusion
Associated with one or block lines of codes
The lines of codes must be executed in that order and not interruptible
The corresponding thread acquires the lock
All other threads will wait and serviced in the order
Co-operation
Desirable when one thread is responsible for updating while another
thread needs updated data
Thread(s) needing updated data will request wait() request and
thread remains in wait state
Thread updating data will issue “Notify” or “Notify All” and
releases monitor
22
Synchronized Blocks or statements Synchronized Methods
format synchronized <return type> SomeMethod(<arguments if any>)
synchronized ( object ) {
{ // Method body
statements }
} // end synchronized statement
23
public class Producer implements Runnable { public class Consumer implements Runnable {
private Drop drop; private Drop drop;
public Producer(Drop drop) {
public Consumer(Drop drop) {
this.drop = drop;
this.drop = drop;
}
public void run() }
{ public void run()
String importantInfo[] = { {
"Mares eat oats", Random random = new Random();
"Does eat oats", for (String message = drop.take(); !
"Little lambs eat ivy", message.equals("DONE");
"A kid will eat ivy too“ };
message = drop.take() )
Random random = new Random();
{
for (int i = 0; i < importantInfo.length; i++) \
System.out.format("MESSAGE RECEIVED: %s
%n", message);
{
drop.put(importantInfo[i]); try {
try { Thread.sleep(random.nextInt(5000));
Thread.sleep(random.nextInt(5000)); } catch (InterruptedException e) {}
} catch (InterruptedException e) {} }
} }
drop.put("DONE");
}
}
}
24
public class Drop { public synchronized void put(String message) {
//Message sent from producer to consumer. //Wait until message has been retrieved.
private String message; while (!empty) {
//True if consumer should wait for producer to send try {
message, false wait();
//if producer should wait for consumer to retrieve } catch (InterruptedException e) {}
message. }
private boolean empty = true; //Toggle status.
empty = false;
public synchronized String take() { //Store message.
//Wait until message is available. this.message = message;
while (empty) { //Notify consumer that status has changed.
try { notifyAll();
wait();
}
} catch (InterruptedException e) {} }
}
//Toggle status. public class ProducerConsumerExample {
empty = true; public static void main(String[] args) {
//Notify producer that status has changed. Drop drop = new Drop();
notifyAll(); (new Thread(new Producer(drop))).start();
return message; (new Thread(new Consumer(drop))).start();
}
}
}
25
When a waiting thread (let us call this thread1)
cannot proceed because it is waiting (either directly
or indirectly) for another thread (let us call this
thread2) to proceed, while simultaneously thread2
cannot proceed because it is waiting (either directly
or indirectly) for thread1 to proceed.
The two threads are waiting for each other, so the
actions that would enable each thread to continue
execution can never occur.
26
27
28
29
30
31
There is no best solution.
Best known way of resolving the deadlock is
resource ordering or restructuring the
programming logic.
32
Multitasking and Processes
Lifecycle of a Thread, and thread states – new, runnable, wait, timed wait, blocked, terminated
Threads can wait while the remaining program can continue to execute
Threads can wait for another thread to complete using the ‘join’ method
Use of synchronization for blocks of code or a method to allow us to manipulate data and preventing
blocking.
Deadlocks can still occur when two threads are waiting for an object to be released by the other thread
( could be directly or indirectly)
33
Q&A
34