Threads in Java
Processes and Threads
Processes
process has self-contained executionenvironment .
Has complete set of runtime resourcesincluding memory space.
Synonymous with program or application.
Most implementations of the Java virtualmachine run as single process.
Processes and Threads
Threads
thread is flow of control
thread is series of executed statements
thread is nested sequence of method calls.
Threads exist within process
Every process has at least one.
Start execution with “Main Thread” but anapplication can be divided into many.
Concurrent programming
Multiple Threads
Creating Threads
Program always has at least one thread: the one created whenthe program begins execution.
In normal Java application program, this thread starts at thebeginning of main().
To start the execution of thread, you call the start() methodfor the Thread object.
The code that executes in new thread is always methodcalled run(), which is public, accepts no arguments, anddoesn’t return value.
Threads other than the main thread in program always startin the run() method for the object that represents the thread.
Threads
Defining and Starting a Thread
Create an object of java.lang.Thread class.
Two ways.
1.One way is to define your class as subclass ofThread and provide definition of the methodrun(), which overrides the inherited method.
2.The other possibility is to define your class asimplementing the interface Runnable, whichdeclares the run() method, and then create aThread object in your class when you need it.
Thread Class Methods
Method Meaning
getName Obtain a thread’s name.
getPriority Obtain a thread’s priority.
isAlive Determine if a thread is still running.
join Wait for a thread to terminate.
run Entry point for the thread.
sleep Suspend a thread for a period of time.
start Start a thread by calling its runmethod.
Single Thread: Example
// Controlling the main Thread.
class CurrentThreadDemo {
public static void main(String args[]) {
Thread t = Thread.currentThread();
System.out.println("Current thread: " + t);
// change the name of the thread
t.setName("My Thread");
System.out.println("After name change: " + t);
try {
for(int n = 5; n > 0; n--) {
System.out.println(n);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted");
}}}
Single Thread: Example Output
Current thread: Thread[main,5,main]
After name change: Thread[My Thread,5,main]
5
4
3
2
1
Runnable Object
The Runnable interface defines a singlemethod, run, meant to contain the codeexecuted in the thread.
Example 1: Through Runnable Interface
public class HelloRunnable implements Runnable
 {
public void run()
{
System.out.println("Hello from a thread!");
}
public static void main(String args[])
{
(new Thread(new HelloRunnable())).start();
 }
}
public class HR implements Runnable
 {
public void run()
{
System.out.println("Hello from a thread!");
}
public static void main(String args[])
{
HR r=new HR();
Thread t=new Thread(r);
t.start();
 } }
Example 1: Through Runnable Interface
SubClass Thread
An application can subclass Thread,providing its own implementation of run.
public class HelloThread extends Thread
{
public void run()
{
     System.out.println("Hello from a thread!");
 }
     public static void main(String args[])
{
       (new HelloThread()).start();
   }
 }
Example: Through Thread Class
public class HR extends Thread
{
public void run()
{
     System.out.println("Hello from a thread!");
 }
     public static void main(String args[])
{
HR r=new HR();
r.start();
   } }
Example: Through Thread Class
Pausing Execution with Sleep
Thread.sleep causes the current thread tosuspend execution for a specified period.
sleep().
Takes time in milliseconds
Interrupts can terminate the sleep period.
Example 1: Sleep Message
public class SleepMessages
{
public static void main(String args[]) throws InterruptedException
 {
    String importantInfo[] = { "Mares eat oats", "Does eat oats", "Littlelambs eat ivy", "A kid will eat ivy too“ };
 for (int i = 0; i < importantInfo.length; i++)
 {
      Thread.sleep(4000);
     System.out.println(importantInfo[i]);
 }
 }
}
OUTPUT: Sleep Message
class NewThread implements Runnable {
Thread t;
NewThread() {
// Create a new, second thread
t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
t.start(); // Start the thread
}
// This is the entry point for the second thread.
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
Thread.sleep(500);}}
catch (InterruptedException e) {
System.out.println("Child interrupted.");}
System.out.println("Exiting child thread.");}}
Example 2: Through Runnable Interface
class ThreadDemo {
public static void main(String args[]) {
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}}
catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");}}
Example 2: Through Runnable Interface
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.
Example 2: Through Runnable InterfaceOutput
Stopping Threads: Interrupt
An interrupt is an indication to thread thatit should stop what it is doing and dosomething else.
thread sends an interrupt by invokinginterrupt() on the Thread object.
Interrupt Status Flag
Interrupt status flag
Invoking Thread.interrupt sets the flag
Method
Description
isInterrupted()
Check if the thread's interrupt() method hasbeen called (this does not clear the interruptedflag).
isAlive()
Tests if this thread is alive. thread is alive if ithas been started and has not yet died.
Daemon and User Threads
The call to setDaemon(true), in theTryThread constructor makes the thread thatis created daemon thread
daemon thread:
 Background thread that is subordinate to thethread that creates it.
 When the thread that created the daemon threadends, the daemon thread dies with it.
Threads that run indefinitely should usuallydefined as daemon threads
Daemon and User Threads
thread that is not daemon thread iscalled user thread :
Typically  used for threads that run finite time
It must be explicitly stopped or destroyed, or itsrun method must return
You can only call setDaemon() for threadbefore it starts
Daemon and User Threads
Main Thread
thread1.setDaemon(true);
thread1.start();
thread2.setDaemon(true);
thread2.start();
thread3.start();
return;
Main Thread
thread1.setDaemon(true);
thread1.start();
thread2.setDaemon(true);
thread2.start();
thread3.start();
return;
thread 1
created as adaemon thread
thread 1
created as adaemon thread
thread 2
created as adaemon thread
thread 2
created as adaemon thread
thread 3
created as auser thread
thread 3
created as auser thread
Ends the main thread.All daemon threadscreated in the mainthread will end at thispoint
Must beexplicitlystopped ordestroyed, orits runmethod mustreturn
Example
import java.io.IOException;
public class TryThread extends Thread
{
public TryThread(String firstName, String secondName, long delay) {
this.firstName = firstName; // Store the first name
this.secondName = secondName; // Store the second name
aWhile = delay; // Store the delay
setDaemon(true); // Thread is daemon
}
public static void main(String[] args) {
// Create three threads
Thread first = new TryThread("Hopalong ", "Cassidy ", 200L);
Thread second = new TryThread("Marilyn ", "Monroe ", 300L);
Thread third = new TryThread("Slim ", "Pickens ", 500L);
System.out.println("Press Enter when you have had enough...\n");
Example
first.start(); // Start the first thread
second.start(); // Start the second thread
third.start(); // Start the third thread
try {
System.in.read(); // Wait until Enter key pressed
System.out.println("Enter pressed...\n");
} catch (IOException e) { // Handle IO exception
System.out.println(e); // Output the exception
}
System.out.println("Ending main()");
return;
}
// Method where thread execution will start
public void run() {
try {
Example
while(true) { // Loop indefinitely...
System.out.print(firstName); // Output first name
sleep(aWhile); // Wait aWhile msec.
System.out.print(secondName + "\n"); // Output second name
}
}
catch(InterruptedException e)
{ // Handle thread interruption
System.out.println(firstName + secondName + e); // Output the exception
}
}
private String firstName; // Store for first name
private String secondName; // Store for second name
private long aWhile; // Delay in milliseconds
}
Output
Connecting Threads
Calling the join() method with no argumentswill halt the current thread for as long as ittakes the specified thread to die
or with argument to specify the number ofmilliseconds to wait for the death of thread
thread1.join(); // suspend the current thread until the thread1 dies
thread1.join(); // suspend the current thread until the thread1 dies
thread1.join(1000); // Wait up to 1 second for thread1 to die
thread1.join(1000); // Wait up to 1 second for thread1 to die
Thread Scheduling
Synchronization
The objective of synchronization is toensure that when several threads wantaccess to single resource, only one threadcan access it at any given time.
Two ways to manage threads
manage code at the method level.
manage code at the block level
t
Why to synchronize  ?
i + 1;
(=   31)
i + 1;
(=   31)
starting value of i is 30
starting value of i is 30
= i - 1;
= i - 1;
value of i is 31 ??
(it should be 30)
value of i is 31 ??
(it should be 30)
thread 2
thread 1
i
30
30
i
29
29
Synchronized Methods
Make methods mutually Exclusive.
Using keyword Synchronized.
Locking and Unlocking
Example
class MyClass {
synchronized public void method1() {
// Code for the method...
}
synchronized public void method2() {
// Code for the method...
}
public void method3() {
// Code for the method...
}
}
For the same objectinstance only onesynchronized method canbe executing at one time,because that method willhave set the lock thatprevents any othersynchronized methodfrom starting.
Example
LAB TASK 1
1.Create a simple java program
2.Having just one thread - the main thread.
3.Add a function which contains a loop thatruns 10 times.
4.Display the name of the thread at each stepwith “1 sec” pause at each step.
Note: Code Must handle InterruptedException
Output
output:
thread main step 0
thread main step 1
thread main step 2
thread main step 3
...
thread main step 99
LAB TASK 2
1.Creating two parallel threads in “Main Thread” byimplementing the Runnable interface
2.Add a "run" method. { write for loop which displaysthe names of threads}
3.Start both threads in Main
4.Introduce the delay of “1 sec” for overlappingexecution of both threads.
Output
output:
thread Thread-0 step 0thread Thread-1 step 0thread Thread-0 step 1thread Thread-1 step 1thread Thread-0 step 2thread Thread-1 step 2thread Thread-0 step 3thread Thread-1 step 3
...
LAB TASK 3
Repeat “LAB TASK 2” by deriving our classfrom the "Thread" class.
Output
output:
thread Thread-0 step 0thread Thread-1 step 0thread Thread-0 step 1thread Thread-1 step 1thread Thread-0 step 2thread Thread-1 step 2thread Thread-0 step 3thread Thread-1 step 3
...