Threads in java

Introduction
• Thread objects are the basis for multithreaded
programming.
• Multi-threaded programming allows a single
program to conduct concurrently running
threads that perform different tasks.

Defined in java.lang.Thread

Thread States
  – Born state
         • Thread was just created
  – Ready state
         • Thread’s start method invoked
         • Thread can now execute
  – Running state
         • Thread is assigned a processor and running
  – Dead state
         • Thread has completed or exited
         • Eventually disposed of by system 

Thread Life-Cycle 



Priorities• Java thread priority
      – Priority in range 1-10
Timeslicing
     – Each thread assigned time on the processor
       (called a quantum)
     – Keeps highest priority threads running
     – Context Switching

Priorities and Scheduling 

Executing Threads
• Sleep state
     – Thread method sleep called
     – Thread sleeps for a set time interval then awakens

1 // ThreadTester.java
2 // Multiple threads printing at different intervals.
3
4 public class ThreadTester {
5
6 public static void main( String [] args )
7 {
8 // create and name each thread
9 PrintThread thread1 = new PrintThread( "thread1" );
10 PrintThread thread2 = new PrintThread( "thread2" );
11 PrintThread thread3 = new PrintThread( "thread3" );
12
13 System.err.println( "Starting threads" );
14
15 thread1.start(); // start thread1 and place it in ready state
16 thread2.start(); // start thread2 and place it in ready state
17 thread3.start(); // start thread3 and place it in ready state
18
19 System.err.println( "Threads started, main ends\n" );
20
21 } // end main
22
23 } // end class ThreadTester
25 // class PrintThread controls thread execution
26 class PrintThread extends Thread {
27 private int sleepTime;
28
29 // assign name to thread by calling superclass constructor
30 public PrintThread( String name )
31 {
32 super( name );
33
34 // pick random sleep time between 0 and 5 seconds
35 sleepTime = ( int ) ( Math.random() * 5001 );
36 }
37
38 // method run is the code to be executed by new thread
39 public void run()
40 {
41 // put thread to sleep for sleepTime amount of time
42 try {
43 System.err.println(getName() + " going to sleep for " + sleepTime );
44 Thread.sleep( sleepTime );
45 }
49 // if thread interrupted during sleep, print stack trace
50 catch ( InterruptedException exception ) {
51 exception.printStackTrace();
52 }
53
54 // print thread name
55 System.err.println( getName() + " done sleeping" );
56
57 } // end method run
58
59 } // end class PrintThread 
Starting threads
Threads started, main ends
thread1 going to sleep for 1217
thread2 going to sleep for 3989
thread3 going to sleep for 662
thread3 done sleeping
thread1 done sleeping
thread2 done sleeping

Starting threads
thread1 going to sleep for 314
thread2 going to sleep for 1990
Threads started, main ends
thread3 going to sleep for 3016
thread1 done sleeping
thread2 done sleeping
thread3 done sleeping

Simplest Thread
• Thread t = new Thread();
• t.start();
• New thread created
• Doesn’t do anything
• Dies at the instant its born
• Missing anything?
– What job should the thread perform?

Call Stack
• Each Thread have individual Call Stack
• Must keep track of which statement is
currently executing on the thread’s stack

Sequence of Running
1. JVM calles main thread
    – public static void main(String[] args)
2. main() starts a new thread
     – Runnable r = new MyThreadJob();
     – Thread t = new Thread(r);
     – t.start();
     – Method m = new Method();

3. JVM switches between the user thread ‘t’
and original ‘main’ thread. 

Runnable
• A Thread object needs a job to perform
• The first method that is loaded in the stack is
    – run()
    – public void run() {
// code that will be run by the new thread
}

• Runnable
    – An interface that should be implemented by the
       Job class
• A class that implements this interface can
provide the “body” of a thread
• Runnable defines only method
    – run()

Example
public class MyRunnable implements Runnable {
public void run() {
go();
}
public void go() {
doMore();
}
public void doMore() {
System.out.println(“top o’ the stack”);
}
}

 class ThreadTester {
public static void main (String[] args) {
Runnable threadJob = new MyRunnable();
Thread myThread = new Thread(threadJob);
myThread .start();
System.out.println(“back in main”);
}
}

class ThreadTester {
public static void main (String[] args) {
Runnable threadJob = new MyRunnable();
Thread myThread = new Thread(threadJob);
myThread .start();

System.out.println(“back in main”);
}
}

Questions
• A job can be created by implementing
“Runnable”, or creating sub-class of Thread
overriding “run()” method. Which one is
better?
– Runnable.
– In OO perspective, Thread and Job are two
separate things.
Can we reuse a Thread Object?
• No
• After a Thread completes it’s run method, it is
in “dead”. Call stack is freed
• The object may be available in heap
  – Will act as normal object, not like a thread

The Thread Class

yield() 
• Temporarily releases time for other threads
• E.g.
public void run() {
for (int i = 1; i <= lastNum; i++) {
System.out.print(" " + i);
Thread.yield();
}
}

Static sleep()
• The sleep(long mills) method puts the thread
to sleep for the specified time in milliseconds

public void run() {
for (int i = 1; i <= lastNum; i++) {
System.out.print(" " + i);
try {
if (i >= 50) Thread.sleep(1);
}
catch (InterruptedException ex)
{
}
}
}

join()
• Use the join() method to force one thread to
wait for another thread to finish

public void run() {
Thread thread4 = new Thread(
new PrintChar('c', 40));
thread4.start();

try {
for (int i = 1; i <= lastNum; i++) {
System.out.print(" " + i);
if (i == 50) thread4.join();
}
}
catch (InterruptedException ex) {
}
}

Thread methods
isAlive ( )
• Method used to find out the state of a thread.
• Returns true:
      – thread is in the Ready, Blocked, or Running state
• Returns false:
      – thread is new and has not started or if it is finished.

interrupt ( )
• If a thread is currently in the Ready or Running state
       – its interrupted flag is set;
• If a thread is currently blocked
      – it is awakened and enters the Ready state, and an
java.io.InterruptedException is thrown.
• The isInterrupt() method tests whether the thread is interrupted.
The deprecated stop(), suspend(), and resume() Methods
• The Thread class also contains the stop(), suspend(), and
resume() methods.
• As of Java 2, these methods are deprecated (or outdated)
      – Because they are known to be inherently unsafe.
• You should assign null to a Thread variable to indicate that it is
stopped rather than use the stop() method.
  
Thread Priority
• Each thread is assigned a default priority of
     – Thread.NORM_PRIORITY
     – constant of 5.
• You can reset the priority using
     – setPriority(int priority).
• Some constants for priorities include
       – Thread.MIN_PRIORITY
       – Thread.MAX_PRIORITY
       – Thread.NORM_PRIORITY
• By default, a thread has the priority level of the thread
that created it.

Thread Scheduling
• An operating system’s thread scheduler
determines which thread runs next.
• Most operating systems use timeslicing for
threads of equal priority.
• Preemptive scheduling: when a thread of
higher priority enters the running state, it
preempts the current thread.
• Starvation: Higher-priority threads can
postpone (possible forever) the execution of
lower-priority threads.

Inconsistency
• Critical application
– Inconsistency
• E.g. multiple access in same bank account
– A reads balance and goes to sleep
– B reads balance and withdraws some money
– A starts running
– A withdraws some money and updates final
– ????

Synchronize
• Need a lock on critical section
• Make the method atomic
   – Synchronized keyword
• While A enters the method, it obtains a lock
• B cannot enter the method until A leaves the
method and releases the lock
  – Ensures consistancy

private synchronized void makeWithdrawal(int amount) {
if (account.getBalance() >= amount) {
System.out.println(Thread.currentThread().getName() + “ is about to withdraw”);
try {
System.out.println(Thread.currentThread().getName() + “ is going to sleep”);
Thread.sleep(500);
} catch(InterruptedException ex) {ex.printStackTrace(); }
System.out.println(Thread.currentThread().getName() + “ woke up.”);
account.withdraw(amount);
System.out.println(Thread.currentThread().getName() + “ completes the withdrawl”);
} else {
System.out.println(“Sorry, not enough for “ + Thread.currentThread().getName());
}
}
 
Copyright © C Program | Java | OpenGL Programming | Hadoop at Computaholics