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

Unit 5 - Java Multithreading

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Unit 5 - Java Multithreading

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Advanced Programming

/
Java Programming
By Melese E.

Tuesday, May 21, 2024 By Melese E., Department of Computer Science 1


Advanced Programming
/
Java Programming

Multi-threading Concept

Tuesday, May 21, 2024 By Melese E., Department of Computer Science 2


Java Multi-threading
• A multithreaded program contains two or more parts that can run concurrently
• Each part of such a program (a single program) is called a thread, and each thread defines a
separate path of execution
• Thus, multithreading is a specialized form of multitasking – thread-based multitasking
• Take for example, MS Word, while you are editing (this is one task), MS Word automatically saves your document
(a second task) simultaneously
• Another form of multitasking is process-based multitasking – two or more programs running in parallel
(while using MS Word, you can listen to the music using Windows Media Player – these two are separate
programs or processes)
• Java provides built-in support for multithreaded programming.
• Threads exist in several states
• Running – currently using the CPU
• Ready to run – as soon as it gets the CPU
• Suspended – a thread that temporarily halts its activity – a suspended thread can then be
resumed allowing it to pick up where it left off
• Blocked – a thread is in block state if it is waiting for a resource (disk file, network, etc)
• Terminated – a thread that halts its execution – once terminated cannot be resumed

Tuesday, May 21, 2024 By Melese E., Department of Computer Science 3


Java Multi-threading
• Thread Priority
• Java assigns to each thread a priority that determines how that thread should be
treated with respect to the others
• A thread’s priority is used to decide when to switch from one running thread to the
next
• This is called a context switch
• The rules that determine when a context switch takes place are simple
• A thread can voluntarily relinquish control. This occurs when explicitly yielding, sleeping, or
when blocked. In this scenario, all other threads are examined, and the highest-priority
thread that is ready to run is given the CPU
• A thread can be preempted by a higher-priority thread. In this case, a lower-priority thread
that does not yield the processor is simply preempted—no matter what it is doing—by a
higher-priority thread. Basically, as soon as a higher-priority thread wants to run, it does. This
is called preemptive multitasking
• In cases where two threads with the same priority are competing for CPU cycles, the
situation is a bit complicated.
• For some operating systems, threads of equal priority are time-sliced automatically in round-
robin fashion.
• For other types of operating systems, threads of equal priority must voluntarily yield control
to their peers. If they don’t, the other threads will not run

Tuesday, May 21, 2024 By Melese E., Department of Computer Science 4


Java Multi-threading
• Synchronization
• Because multithreading introduces an asynchronous behavior to your
programs, there must be a way for you to enforce synchronicity when you
need it.
• For example, if you want two threads to communicate and share a complicated data
structure, such as a linked list, you need some way to ensure that they don’t conflict with
each other
• That is, you must prevent one thread from writing data while another thread is in the
middle of reading it
• For this purpose, Java implements an elegant twist on an age-old model of
interprocess synchronization: the monitor
• You can think of a monitor as a very small box that can hold only one thread.
• Once a thread enters a monitor, all other threads must wait until that thread exits the
monitor.
• In this way, a monitor can be used to protect a shared asset from being manipulated by more
than one thread at a time
Tuesday, May 21, 2024 By Melese E., Department of Computer Science 5
Java Multi-threading
• To create a multithreaded program in Java – Java provides
• The Thread class
• The Runnable interface
• To create a new thread, your program will either extend Thread class or
implement the Runnable interface.
• The Thread class defines several methods that help manage threads – some of
them are
• getName() – obtain thread’s name
• getPriority() – obtain 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 run method
• setName() – sets the name of the thread
• setPriority() – sets the priority of the thread
• getState( ) – obtain the state of a thread (BLOCKED, RUNNABLE, WAITING, )

Tuesday, May 21, 2024 By Melese E., Department of Computer Science 6


Java Multi-threading
• The Main Thread
• When a Java program starts up, one thread begins running immediately.
• This is usually called the main thread of your program, because it is the one that is
executed when your program begins.
• The main thread is important for two reasons:
• It is the thread from which other “child” threads will be spawned
• Often, it must be the last thread to finish execution because it performs various
shutdown actions
• Although the main thread is created automatically when your program is
started, it can be controlled through a Thread object.
• To do so, you must obtain a reference to it by calling the method currentThread( )
• static Thread currentThread( )

Tuesday, May 21, 2024 By Melese E., Department of Computer Science 7


Java Multi-threading
public class Threading1 {
public static void main(String[] args) throws InterruptedException {
Thread t = Thread.currentThread();
System.out.println(t.getName());
t.setName("This is the Main Thread");
System.out.println(t.getName());
System.out.println(t.getPriority());
System.out.println(t.getState());
t.sleep(2000);
System.out.println("After suspending for 2 seconds");
}
}

Tuesday, May 21, 2024 By Melese E., Department of Computer Science 8


Java Multi-threading
• Creating a Thread – there are two options
• Option One: extending the Thread class
• Option two: implementing the Runnable interface
• The choice is yours
• In both cases, your class needs to have the run method
• Overriding the run method in the case of extending Thread class
• Implementing the run method in the case of implementing the Runnable
• The run method looks as follows

public void run() {
//put what your thread should do here
}

Tuesday, May 21, 2024 By Melese E., Department of Computer Science 9


Java Multi-threading
• Implementing the Runnable interface
public class Threading2 implements Runnable{
Thread t;
Threading2(){
t = new Thread(this, "example");
}
public void run(){
System.out.println("this is a new thread")
System.out.println(t.getName());
System.out.println("You can do whatever you want to do here");
}
}
• To use it you need to create an instance of the Threading2 class and call the
start method – in the main method or in another thread
• Threading2 th = new Threading2();
• th.t.start();
Tuesday, May 21, 2024 By Melese E., Department of Computer Science 10
Java Multi-threading
• The following program creates a new threading using the previous
implementation

class Main{
public static void main(String args[]){
System.out.println("in the main method");
Threading2 th = new Threading2();
System.out.println(th.t.getName());
th.t.start();
System.out.println(Thread.currentThread().getName());
System.out.println("This is also in the main thread");
}
}

Tuesday, May 21, 2024 By Melese E., Department of Computer Science 11


Java Multi-threading
• Extending the Thread class

public class Threading3 extends Thread{
Threading3(){
setName("example");
}
public void run(){
System.out.println("this is a new thread");
System.out.println(getName());
System.out.println("You can do whatever you want to do here");
}
}
• To use it you need to create an instance of the Threading3 class and call the
start method – in the main method or in another thread
• Threading3 th = new Threading3();
• th.start();

Tuesday, May 21, 2024 By Melese E., Department of Computer Science 12


Java Multi-threading
• The following program creates a new threading using the previous
implementation – extending the Thread class

class Main{
public static void main(String args[]){
System.out.println("in the main method");
Threading3 th = new Threading3();
System.out.println(th.getName());
th.start();
System.out.println(Thread.currentThread().getName());
System.out.println("This is also in the main thread");
}
}

Tuesday, May 21, 2024 By Melese E., Department of Computer Science 13


Java Multi-threading
• The previous examples, create one thread
• This means there are two threads – the main thread and the example thread
• You may need to create multiple threads
• Same task – using multiple instances of the same class and/or
• Having multiple implementation for each thread
• Using the previous example you can create as many threads as you need –
but all threads perform same task
• Threading3 t1 = new Threading3();
• Threading3 t2 = new Threading3();
• t1.start();
• t2.start();
• You can create an array of threads as follows

Threading3 threads[] = new Threading3[5];
For(int i=0; i<5; i++) {
Threads[i] = new Threading3();
Threads[i].start();
}

Tuesday, May 21, 2024 By Melese E., Department of Computer Science 14


Java Multi-threading
• You may have two or more threads that perform different task
• For each task, you need to have a separate implementation of thread
• You can create as many threads as you need
class TaskOne extends Thread{ class TaskTwo extends Thread{
TaskOne(){ TaskTwo(){
super(“Task One”); super(“Task Two”);
} }
public void run(){ public void run(){
System.out.println(“Thread task one”); System.out.println(“Thread task Two”);
} }
} }

• Then you use them as follows


• TaskOne t = new TaskOne();
• TaskTwo t2 = new TaskTwo();
• t.start();
• t2.start()
Tuesday, May 21, 2024 By Melese E., Department of Computer Science 15
Java Multi-threading
• Thread Priority
• There are two methods to work with priority
• final int getPriority()
• final void setPriority(int level)
• The priority level must be within Thread.MIN_PRIORITY and MAX_PRIORITY
(which is one (1) and ten (10) respectively)
• The default priority is Thread.NORM_PRIORITY – which is 5 (five)

Tuesday, May 21, 2024 By Melese E., Department of Computer Science 16


Java Multi-threading
• Synchronization
• When two or more threads need access to a shared resource, they need some
way to ensure that the resource will be used by only one thread at a time.
• The process by which this is achieved is called synchronization
• Key to synchronization is the concept of the monitor.
• A monitor is an object that is used as a mutually exclusive lock
• Only one thread can own a monitor at a given time.
• When a thread acquires a lock, it is said to have entered the monitor.
• All other threads attempting to enter the locked monitor will be suspended until the first
thread exits the monitor.
• These other threads are said to be waiting for the monitor.
• A thread that owns a monitor can reenter the same monitor if it so desires
• You can synchronize your code in either of two ways. Both involve the use of
the synchronized keyword
• Using a synchronized method
• Using a synchronized statement

Tuesday, May 21, 2024 By Melese E., Department of Computer Science 17


Java Multi-threading
• Synchronization – using a synchronized method
• A synchronized method is a method that is modified with the synchronized
keyword
• While a thread is inside a synchronized method, all other threads that try to
call it (or any other synchronized method) on the same instance have to wait.
• To exit the monitor and relinquish control of the object to the next waiting
thread, the owner of the monitor simply returns from the synchronized
method
• In the following example program, nothing exists to stop all three threads
from calling the same method, on the same object, at the same time.
• In this case the display method of the object example
• This is known as a race condition, because the three threads are racing each
other to complete the method

Tuesday, May 21, 2024 By Melese E., Department of Computer Science 18


Java Multi-threading
class Example{
void display(String msg, String threadName) throws InterruptedException{ public class ThreadingSync{
System.out.println(threadName + " displays " + msg); public static void main(String[] args){
Thread.sleep(1000); Example example = new Example();
System.out.println(threadName + " displays " + msg + " again"); TheThread th1 = new TheThread("Thread One", example);
} TheThread th2 = new TheThread("Thread Two",example);
} TheThread th3 = new TheThread("Thread Three",example);
class TheThread extends Thread{ th1.start();
Example ex; th2.start();
TheThread(String name, Example e ){ th3.start();
super(name);
}
ex = e;
}
}
public void run(){
try{
ex.display( "\'THE MESSAGE\'",getName());
}catch(InterruptedException ie){

}}} Tuesday, May 21, 2024 By Melese E., Department of Computer Science 19
Java Multi-threading
• Synchronization – using a synchronized method
• Modifying the display method in the Example class by modifying it with the
synchronized keyword prevents threads to enter the method at the same
time
synchronized void display(String msg, String threadName) throws InterruptedException{
System.out.println(threadName + " displays " + msg);
Thread.sleep(1000);
System.out.println(threadName + " displays " + msg + " again");
}

Tuesday, May 21, 2024 By Melese E., Department of Computer Science 20


Java Multi-threading
• Synchronization – using the }
synchronized statement public void run(){
try{
• Some times you may not be able to synchronized(ex){
use synchronized methods (may be
ex.display( "\'THE
you have no access to the source MESSAGE\'",getName());
code of the methods) }
• In such cases use the synchronized }
block statement
catch(InterruptedException ie){
• Include the statements (that make
the threads into a race condition) }
inside the synchronized block }
class TheThread extends Thread{ }
Example ex;
TheThread(String name, Example e ){
super(name);
ex = e;
Tuesday, May 21, 2024 By Melese E., Department of Computer Science 21
The End!

Tuesday, May 21, 2024 By Melese E., Department of Computer Science 22

You might also like