0% found this document useful (0 votes)
53 views

Threads and Java

The document summarizes Alex Thomas's presentation on threads and concurrency in Java. It discusses tasks being performed concurrently through threads rather than sequentially. It covers the lifecycle of threads, creating and running threads, setting thread priorities, and using methods like sleep() to pause thread execution. The presentation provides an introduction to concurrency and threading concepts in Java.

Uploaded by

kuticat
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
53 views

Threads and Java

The document summarizes Alex Thomas's presentation on threads and concurrency in Java. It discusses tasks being performed concurrently through threads rather than sequentially. It covers the lifecycle of threads, creating and running threads, setting thread priorities, and using methods like sleep() to pause thread execution. The presentation provides an introduction to concurrency and threading concepts in Java.

Uploaded by

kuticat
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 34

A presentation by Alex Thomas on

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

• As humans we can do probably 4 or 5 activities …

• How about computers?

• 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

• Why wait for one application?


– Not very efficient…
– Important tasks will on hold

4
5
6
7
• Many times, an application package will
contain many associated executables

• An OS does not identify the various


executables as belonging to one package

• So they run as different processes.

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

 To directly control thread creation and management


 Instantiate the thread when needed - asynchronous

 Abstract thread management from rest of you application –


using extractor

 Create instances of Thread


 Extend the thread class and override its run() method
 Implement a ‘Runnable’ object

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()

stop()/ stop(throwable t)/


stop1()
run() Subclasses will override this method SUSPEND/RESUME are deprecated
Your program specific code goes here Thread.suspend is inherently deadlock-prone. If the
target thread holds a lock on the monitor protecting a
Sleep(long millis), Sleep in period of millis critical system resource when it is suspended, no thread
Sleep(long millis, int nano ) can access this resource until the target thread is
resumed. If the thread that would resume the target
Yield Willingly allow thread to give up processor
thread attempts to lock this monitor prior to calling
resume, deadlock results. Such deadlocks typically
Suspend/resume Allow thread to pause and restart manifest themselves as "frozen" processes.

IsAlive() Check if thread is alive

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)

 A checked exception called 'InterruptedException'


 is thrown by the sleep() method if another process attempts to interrupt the
thread before the specified time-interval is over.
 This Exception should be handled when the sleep method is used.

 We have to use try{….}catch{…} blocks

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

Typically your object will be the this operator, if we are synchronizing


in that objects.
public synchronized void set( int value ) throws InteruptException
public void set( int value ) throws InterruptException {
{ // place value into buffer
// place value into buffer // while there are no empty locations, place thread in waiting state
// while there are no empty locations, place thread in waiting state
buffer = value; // set new buffer value
Synchronized(this)
// indicate producer cannot store another value
{
// until consumer retrieves current buffer value
buffer = value; // set new buffer value occupied = true;
// indicate producer cannot store another value displayState( "Producer writes " + buffer );
// until consumer retrieves current buffer value
occupied = true; notifyAll(); // tell waiting thread(s) to enter runnable state
}
displayState( "Producer writes " + buffer );

notifyAll(); // tell waiting thread(s) to enter runnable state


}
}

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

 Thread allow parallelization in our programming activity and logics.

 Thread do not require new memory and hence termed Lightweight

 Lifecycle of a Thread, and thread states – new, runnable, wait, timed wait, blocked, terminated

 Creating Threads - runnable and thread extends, a third kind extractors

 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.

 We can perform inter-thread communication using a shared code and synchronization

 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

You might also like