Download as pdf or txt
Download as pdf or txt
You are on page 1of 22

Threading

Day 6 - morning

4/30/2024 Dr. Randima Dinalankara 1


What is a thread?

• A thread is a sub process of a process/programme.


• A programme/process can have multiple threads.
• Threads are independent.
• Threads in a process share same memory space.
• Threads can run parallelly.

4/30/2024 Dr. Randima Dinalankara 2


Life Cycle of a thread

1. Newborn - thread is just created

2. Runnable - thread is ready to run and waiting for a processor

3. Running - thread is running for a given time

4. Blocked - thread is prevented from entering to running or runnable state

5. Terminated - It has completed the run() method and reached the end of life.
4/30/2024 Dr. Randima Dinalankara 3
Implement a simple thread

1. Import class to the file

2. Extend the class with Thread super class

3. Implement run() method

4. Create a thread object and call start() method

4/30/2024 Dr. Randima Dinalankara 4


Implement a simple thread programme example
import java.lang.Thread; 1

public class MultiThreadingExample1 extends Thread { 2

public static void main(String[] args) {


MultiThreadingExample1 thread = new MultiThreadingExample1();
thread.start(); 4
System.out.println("Outside the thread ...");
}

public void run(){ 3


System.out.println("This is from the thread ...");
}
}
4/30/2024 Dr. Randima Dinalankara 5
Stopping a thread

• Use the <thread name>.stop() method.

• It will stop the thread.

• Thread will move to dead state.

4/30/2024 Dr. Randima Dinalankara 6


Blocking a thread

• Temporarily blocked or suspended entering the runnable


or running state.

• Use following methods


– sleep() - move to runnable state once sleep time is elapsed

– suspend() - resume() method ends the suspension

– wait() - notify() methods ends the waiting

4/30/2024 Dr. Randima Dinalankara 7


Action Performing Methods of Thread Class
Method Definition
start() Start executing the thread
stop() Stop executing the thread
run() Operations performed by the thread
sleep() Thread is put on sleep state for perticular period
wait() Put the thread in waiting state
notify() Provide a notificaiton to the waiting thread
resume() Resume the operation of suspended thread
isDeamon() Check whether the thread is in deamon state or not
setDeamon() Set the thread to a deamon thread.

4/30/2024 Dr. Randima Dinalankara 8


Implement Runnable Interface

• Declare the class as implementing Runnable interface

• Implement run() method

• Create an object with Thread Class

• Call the start() method

4/30/2024 Dr. Randima Dinalankara 9


Example - Runnable interface
import java.lang.Thread;

public class MultiThreadingExample1 implements Runnable {

public static void main(String[] args) {


MultiThreadingExample1 obj = new MultiThreadingExample1();
Thread thread = new Thread();
thread.start();
System.out.println("Outside the thread ...");
}

public void run(){


System.out.println("This is from the thread ...");
}
4/30/2024 Dr. Randima Dinalankara 10
}
Multithreading programme (interchanging
output)
public class Thread1 extends Thread {
public void run(){
for(int i=0; i<50; i++){
System.out.print("A");
}
}
}

public class Thread2 extends Thread {


public void run(){
for(int i=0; i<50; i++){
System.out.print("B");
}
}
4/30/2024 Dr. Randima Dinalankara 11
}
Multithreading programme (interchanging
output)
In the main()
Thread1 t1 = new Thread1();
Thread2 t2 = new Thread2();
t1.start();
t2.start();

The output of the programme would print the letter ‘A’ and ‘B’
interchangable manner.

4/30/2024 Dr. Randima Dinalankara 12


Thread name

• Name of the thread can be observed using getName()


method.
– <thread>.getName()

4/30/2024 Dr. Randima Dinalankara 13


Priority of a thread

• Thread can assign a priority.


• Processor will give chance to the thread(s) with highest
priority in the runnable state.

• Observe the priority of a thread


– <thread>.getPriority()

• Set the priority of a thread


– <thread>.setPriority(<integer between 1 and 10>)
4/30/2024 Dr. Randima Dinalankara 14
Priority of a thread (cont.)

• In general, the priority value for all the threads are set at 5.
• So all the threads have the same priority.

• Change the priority of t1 and t2 threads in previous


example and rerun the programme. Observe the output.
t1.setPriority(2);
t2.setPriority(8);
t1.start();
t2.start();
4/30/2024 Dr. Randima Dinalankara 15
Priority of a thread (cont.)

• To observe the priority of the thread, use getPriority()

• Syntax
– <Thread name>.getPriority()

• If the previous programme is modified,


System.out.println(t1.getPriority());
System.out.println(t2.getPriority());

4/30/2024 Dr. Randima Dinalankara 16


currentThread()

• To observe the name and priority of the thread which is


running, use the currentThread() as follows
currentThread().getName()
currentThread().getPriority()

4/30/2024 Dr. Randima Dinalankara 17


currentThread() example myThread Class
import java.lang.Thread;

public class myThread extends Thread{


public void run(){
System.out.println("Thread name - "+currentThread().getName());
System.out.println("Thread priority - " +
currentThread().getPriority());
}
}

4/30/2024 Dr. Randima Dinalankara 18


currentThread() example main function
public class threadExample{
public static void main(String[] args){
System.out.println("Thread name -"+
Thread.currentThread().getName());
System.out.println("Thread priority -"+
Thread.currentThread().getPriority());

myThread t1 = new myThread();


myThread t2 = new myThread(); Thread name -main
t1.start(); Thread priority -5
t2.start(); Thread name - Thread-0
} Thread priority - 5
Thread name - Thread-1
}
Thread priority - 5
4/30/2024 Dr. Randima Dinalankara 19
Concurrency Issue

• Threads are sharing memory space.


• So, same variable can be shared among the threads.

• However, what will happen if variable is been updated by


multiple threads?
– Check the following example and its output.

4/30/2024 Dr. Randima Dinalankara 20


Concurrency issue - example
public class ThreadExample extends Thread{

public static int count = 0;

public static void main(String[] args) {


ThreadExample userThread = new ThreadExample();
userThread.start();
System.out.println(count);
count++;
System.out.println(count);
} userThread effect
public void run(){ is not visible
count+=100; most of the time
}
4/30/2024 Dr. Randima Dinalankara 21
}
Concurrency issue - solution
public static void main(String[] args) {
ThreadExample userThread = new ThreadExample();
userThread.start();

while(userThread.isAlive()) { This part will be continued


System.out.println("Waiting..."); until the run() is executed
} and the userThread terminates.

System.out.println(count);
count++;
System.out.println(count);
}

4/30/2024 Dr. Randima Dinalankara 22

You might also like