0% found this document useful (0 votes)
177 views30 pages

Java Multithreading Basics Explained

Uploaded by

gauravfoods68
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
177 views30 pages

Java Multithreading Basics Explained

Uploaded by

gauravfoods68
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

UNIT 2: MULTITHREADING

TITLE OF PAPER: ADVANCED JAVA

UNIT 2: MULTITHREADING

1. Threading Basics
 Multithreading in Java is a process of executing multiple threads
simultaneously.

 A thread is a lightweight sub-process, the smallest unit of processing.


Multiprocessing and multithreading, both are used to achieve multitasking. A
thread itself is not a program, a thread cannot run on its own, rather it runs
within a program.

 However, we use multithreading than multiprocessing because threads use a


shared memory area. They don't allocate separate memory area so saves
memory, and context-switching between the threads takes less time than
process.

 A multithreaded program Contains two or more ports that can run concurrently
& each part Can handle a different task at the same time making optimal use of
the available resources Specially when Your Computer has multiple CPUs.

 By definition multitasking is when multiple processes Share Common


processing resources Such as CPU. Multithreading extends the idea of
multitasking into applications where you a Can Subdivide Specific operations
within Single application into individual threads.

 Each of the thread can run in parallel. The OS divides processing time not only
among different applications but also among each thread within an application.
1
UNIT 2: MULTITHREADING

 Multithreading enables to write multiple in a way where multiple activities can


proceed Concurrently in the Same program.

 Advantages -
A] It doesn't block the user because threads are independent and you can
perform multiple operations at the same time.
B] You can perform many operations together, so it saves time.
C] Threads are independent, so it doesn't affect other threads if an exception
occurs in a single thread.

2
UNIT 2: MULTITHREADING

2. Life Cycle of a Thread

 All programmers are familiar with waiting sequential program. You have
probably written a program that displays Hello world or Sort list of names or
Computer a list of prime numbers. This are sequential programs that is each has
a beginning & execution sequence and an and. At any given time during the
runtime of the program there is a single point of execution.
 A thread is similar to the sequential program. describe previously, a single
thread can also have a beginning a sequence and an end.
 A thread Comprises a thread Id, a program Counter register set and a stack. A
thread a Shares the code section, data section and other operating system
resources like Open files with other threads belonging to the Same process. At
any given time during the runtime of the thread there is a single point of
execution. However, a thread itself is not a program. A thread Cannot run on its
own rather it runs within a program.
A] New: A new thread begins its life cycle in a new state it remains in this state until the
prog ram starts the thread it is also referred as bone thread.
B] Runnable: After a new link bone thread is started, the thread becomes runnable a
thread in this state is considered to be exciting its task.

3
UNIT 2: MULTITHREADING

C] Waiting: Sometimes a thread transition to waiting state while the thread waits. For
another thread to perform a task a thread transition back to the runnable state only when
another thread signals the waiting thread to continue the executing.
D] time waiting: a runnable thread can enter in the time waiting state for Specific
interval of time. A thread in this state transition back to the runnable state when that time
interval is expired or when the event it is waiting for occurs.
E] dead :- A runnable method enters in the terminated state when it complete it tasks or
otherwise terminate.

Java provide a Thread class to achieve a thread programming thread class provide
Constructors & methods to create & perform Operations on a thread. Thread class extends
object class and implement runnable interface. Some important method defines in
[Link] thread are show in the following table

4
UNIT 2: MULTITHREADING

S.N Modifier & type Method Description


1 Void Start() It is used to start the execution of thread
2 Void run() It is used to do an action for a thread
3 Static void sleep() It sleeps a thread for the specified amount of
time
4 Thread CurrentThread() It returns a reference to the currently executing
thread object
5 Void join() It waits for a thread to die
6 boolean isAlive It tests if the thread is alive
7 string getName() It returns the name of the thread
8 Void interrupt() It interrupts the thread
9 int activecount() It returns the number of active threads in the
current thread’s thread group
10 Void yield() It causes the currently executing thread object
to pause & allow other threads to execute
temporarily.

3. Creating Threads

Thread Can be created by using two mechanisms:


A. Extending the thread class-
Thread creation by extending thread class:- We create a class that extends the
[Link] thread class this class overrides the run() method available in thread
class.
We can create an object of a new class & call start () to start execution of thread.
Start () invokes the run () on the thread object.
B. Implementing a runnable interface-
Java Runnable is an interface use to execute code on Concurrent thread it is an
interface which is implemented by any class. If we want that the instances of
that class should be executed by a thread the Runnable has an Undefined method
run with write as a return type & it takes no arguments whether output of a class

5
UNIT 2: MULTITHREADING

implementing another is use to create thread the run() involves internet which
execute separately the runnable interface provides Standard set of rules for the
instances of class.
e.g.) Extending thread class.
import [Link].*;
import java [Link];
class Threaddemo extends Thread{
public void run() {
[Link] ("Creating thread");
}
public static void main (string args[]){
threaddemo th= new threaddemo ();
[Link] ();
}
}

e.g) Implementing Runnable interface


import [Link];
public class Threaddemo implements Runnable{
try{
public void run (){
[Link] ("Running a thread");
}
}

6
UNIT 2: MULTITHREADING

public static void main (staing args []){


threaddemo th= new threaddomo ();
thread thread1= new thread (th);
[Link]();
}
}

4. Priorities and Synchronization

1. Priorities

 Java assigned priorities to every thread by default all Threads have their own
priorities but by providing priorities we force of thread to give respect to other. The
thread priority is an integer from one to ten where ‘1’ is minimum priority & '10' is
maximum priority.
 In java thread scheduler can used the thread priorities in the form of integer value to
each of its thread to determine the execution Schedule of thread. The gets the ready
to run state according to their priorities. The thread Scheduler provides the CPU
time to thread of highest priority during ready to run state.
 Priorities are integer value from ‘1’[lowest priority given by the Constant
[Thread.MIN_ PRIORITY], to ‘10’ [highest priority given by the Constant
[Thread.MAX___ PRIORITY] default priority is ‘5’ [Thread.NORM_PRIORITY].
 The method setpriority() is used to set the priority of thread. The getpriority() is
used to get the priority of thread.

7
UNIT 2: MULTITHREADING

2. Synchronization

 When we start two or more threads within a program there may be a situation when
multiple thread tries to access the same resources and finally, they can produce
Unforeseen result due to the concurrency issues.

 E.g., If multiple thread tries to write within a same file, then they may corrupt the
data because one of the threads can override data or while one thread is opening the
same file of the same time another thread might be closing the same file.

 Synchronization is the way to avoid data corruption cause by simultaneous access


to the same data. so, there is need to synchronize the action of multiple threads &
make sure that only resource at one thread can access the a given point in time. This
is implemented using the Concept called monitors.

 Each object in java is associated with a monitor, which thread can lock or unlock.
Only one thread at a time may hold a lock on a monitor. Java programming
language provides a very handy way of creating threads & synchronizing their task
by using Synchronized block.

5. Inter Thread Communication

 Inter-thread communication or Co-operation is all about allowing synchronized


threads to communicate with each other. Cooperation (Inter-thread
communication) is a mechanism in which a thread is paused running in its
critical section and another thread is allowed to enter (or lock) in the same
critical section to be executed. It is implemented by following methods of
Object class:

I)wait() II)notify() III)notifyAll()


8
UNIT 2: MULTITHREADING

I) wait() method
 The wait() method causes current thread to release the lock and wait until either
another thread invokes the notify() method or the notifyAll() method for this
object, or a specified amount of time has elapsed. The current thread must own
this object's monitor, so it must be called from the synchronized method only
otherwise it will throw exception.
Method Description
public final void wait()throws InterruptedException It waits until object is notified.
public final void wait(long timeout)throws It waits for the specified amount of time.
InterruptedException

II) notify() method


 The notify() method wakes up a single thread that is waiting on this object's
monitor. If any threads are waiting on this object, one of them is chosen to be
awakened. The choice is arbitrary and occurs at the discretion of the
implementation.
Syntax: public final void notify()

III) notifyAll() method


 Wakes up all threads that are waiting on this object's monitor.
Syntax: public final void notifyAll()

Difference between wait and sleep


wait() sleep()
The wait() method releases the lock. The sleep() method doesn't release the lock.
It is a method of Object class It is a method of Thread class
It is the non-static method It is the static method
It should be notified by notify() or notifyAll() After the specified amount of time, sleep is
methods completed.
9
UNIT 2: MULTITHREADING

6. Runnable Interface
 Java runnable is an interface use to execute code on Concurrent thread it is an
interface which is implemented by any class if we want that the instance of that
class Should be executed by thread the runnable has an Undefined method run
with the write as a return type.
Syntax:
Runnable runnable = new My Runnable ();
Thread thread = new Thread (runnable);
thread Start();

10
UNIT 2: MULTITHREADING

7. Programs
1) Write a java program to display “Hello Java” message n times on the screen. (Use
Runnable Interface).

import [Link];
class mythread3 implements Runnable
{
Thread t;
public mythread3(String s){
t = new Thread(this,s);
[Link]();
}
public void run() {
Scanner sc = new Scanner([Link]);
[Link]("enter number");
int n=[Link]();
for(int i=0;i<n;i++) {
[Link]([Link]().getName());
try {
[Link](100);
}
catch(Exception e) {

}
11
UNIT 2: MULTITHREADING

}
}
}
public class hellojava {

public static void main(String[] args) {


// TODO Auto-generated method stub
mythread3 m =new mythread3("Hello Java");

12
UNIT 2: MULTITHREADING

2) Write a multithreading program in java to display all the vowels from a given
String. [use thread class]

import [Link].*;
class vowel extends Thread{
String s1;
vowel(String s){
s1=s;
start();
}
public void run() {
[Link]("vowels are");
for(int i=0;i<[Link]();i++) {
char ch =[Link](i);

if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u'||ch=='A'||ch=='E'||ch=='I'||ch=='O'||ch=='
U') {
[Link](" "+ch);
}
}
}
}
public class vowels {
public static void main(String [] args) {
Scanner sc = new Scanner([Link]);
13
UNIT 2: MULTITHREADING

[Link]("Enter string");
String str=[Link]();
vowel v =new vowel(str);
}
}

14
UNIT 2: MULTITHREADING

3) Write a java program which will display priority of current thread.

class mythread1 extends Thread{


mythread1(String s){
super(s);
start();
}
public void run() {
for(int i=0;i<3;i++) {
Thread cur = [Link]();
[Link](Thread.MIN_PRIORITY);
int p = [Link]();
[Link]([Link]().getName());
[Link]("Thread priority"+cur);
}
}
}
class mythread2 extends Thread{
mythread2(String s){
super(s);
start();
}
public void run() {
for(int i=0;i<3;i++) {
15
UNIT 2: MULTITHREADING

Thread cur = [Link]();


[Link](Thread.MAX_PRIORITY);
int p = [Link]();
[Link]([Link]().getName());
[Link]("Thread priority"+cur);
}
}
}
public class priority {

public static void main(String[] args) {


// TODO Auto-generated method stub
mythread1 m1 = new mythread1("mythread1");
mythread2 m2 = new mythread2("mythread2");
}

16
UNIT 2: MULTITHREADING

4) Write a java program using multithreading to execute the table sequentially. (Use
Synchronized Method)

class table
{
void print_table(int n)
{
synchronized(this)
{
for(int i=1;i<=5;i++)
{
[Link](n*i);
try {
[Link](400);
}
catch(Exception e)
{
[Link](e);
}
}
}
}
}
class Mythread extends Thread{
17
UNIT 2: MULTITHREADING

table T = new table();


Mythread(table t)
{
this.T=t;
}
public void run() {
T.print_table(5);
}
}
class Mythread2 extends Thread{
table T = new table();
Mythread2(table t){
this.T=t;
}
public void run() {
T.print_table(100);
}
}
public class Test{

public static void main(String[] args) {


table obj = new table();
Mythread m1 = new Mythread(obj);
Mythread2 m2 = new Mythread2(obj);
18
UNIT 2: MULTITHREADING

[Link]();
[Link]();

}
}

19
UNIT 2: MULTITHREADING

5) Write a java program which will display name and priority of current. Change
name of Thread to Mythread and set the priority to 2 display it on screen.

public class Slip17 {


public static void main(String[] args) {
// TODO Auto-generated method stub
String S;
int p;
Thread t = [Link]();
S = [Link]();
[Link]("\n Current Thread name: "+S);
p = [Link]();
[Link]("\n Current Thread Priority: "+p);
[Link]("My Thread");
S = [Link]();
[Link]("\n Changed Name: "+S);
[Link](2);
p = [Link]();
[Link]("\n Changed Priority: "+p);
}

20
UNIT 2: MULTITHREADING

6) Write a multithreading program in java to display all the alphabets from A to Z


after 3 seconds

public class atoz extends Thread {


char c;
public void run()
{
for(c= 'A'; c<='Z';c++) {
[Link](""+c);
try {
[Link](3000);
}
catch(Exception e) {
[Link](e);
}

}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
atoz t = new atoz();
[Link]();
}
}
21
UNIT 2: MULTITHREADING

7) Write a java program to stimulate traffic signal using multithreading

import [Link];
import [Link];

public class light1 implements Runnable {


public enum Color {RED, ORANGE, GREEN}
private List<Color> light = [Link]([Link], [Link],
[Link]);

private static volatile int counter = 0;


private int i;

private static final Object lock = new Object();

public light1(Color color) {


this.i = [Link](color);
}
public void run() {
try {
synchronized(lock) {
while(true) {
while(counter % [Link]() != i) [Link]();

22
UNIT 2: MULTITHREADING

[Link]([Link]().getName() + "::" + [Link](counter %


[Link]()));
counter++;
[Link](1000);
[Link]();
}
}
} catch(InterruptedException e) {
[Link]();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new Thread(new light1([Link])).start();
new Thread(new light1([Link])).start();
new Thread(new light1([Link])).start();
}

23
UNIT 2: MULTITHREADING

8) Write a multithreading program using Runnable interface to blink text on the


frame.

import [Link];
import [Link];

public class Blinktext extends JFrame implements Runnable {


Thread t;
Label l1;
int f;
JFrame frame;
public Blinktext() {
t=new Thread(this);
[Link]();
setLayout(null);
l1=new Label("HELLO JAVA");
[Link](100,100,100,40);
add(l1);
setSize(300,300);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f=0;
}
public void run()
24
UNIT 2: MULTITHREADING

{
try {
if(f==0) {
[Link](200);
[Link]("");
f=1;
}
if(f==1) {
[Link](200);
[Link]("Hello Java");
f=0;
}
}catch(Exception e) {
[Link](e);
}
run();
}

public static void main(String[] args) {


// TODO Auto-generated method stub
new Blinktext();
}

}
25
UNIT 2: MULTITHREADING

9) Write a java program which will show life cycle (creation, sleep, dead) of a thread
program should be randomly the name of the thread should be hard code thread the
constructor the sleep time will be random integer in range of 0-4999
Class MyThread extends Thread
{ public MyThread(String s)
{
super(s);
}
public void run()
{
[Link](getName()+"thread created.");
while(true)
{
[Link](this);
int s=(int)([Link]()*5000);
[Link](getName()+"is sleeping for :+s+"msec");
try{
[Link](s);
}
catch(Exception e)
{
}
}
}

26
UNIT 2: MULTITHREADING

Class ThreadLifeCycle
{
public static void main(String args[])
{
MyThread t1=new MyThread("Tejas"),t2=new MyThread("Shinde");
[Link]();
[Link]();
try
{
[Link]();
[Link]();
}
catch(Exception e)
{
}
[Link]([Link]()+"thread dead.");
[Link]([Link]()+"thread dead.");
}
}

27
UNIT 2: MULTITHREADING

10) Write a multithreading in java to display number between 1 to 100 continuously


in a text field by clicking on the button (Use runnable interface).
import [Link].*;
import [Link].*;
class ThreadClass extends Frame implements ActionListener,Runnable
{
Button b1;
TextField txt1;
int cnt;
Thread t1 = new Thread(this, “txt1”);
public ThreadClass()
{
setLayout(null);
txt1 = new TextField();
b1 = new Button(“Start”);
[Link](50,50,100,100);
[Link](50,170,100,30);
add(txt1);
[Link](this);
add(b1);
setSize(400,400);
setVisible(true);
cnt=0;
addWindowListener(new WindowAdapter()
28
UNIT 2: MULTITHREADING

{
public void windowClosing(WindowEvent e)
{
[Link](0);
}
});
}
public void actionPerformed(ActionEvent ae)
{
String str;
str=[Link]();
if ([Link](“Start”))
{
[Link]();
}
else if ([Link](“Stop”))
{
[Link]();
}
}
public void run()
{
try
{
29
UNIT 2: MULTITHREADING

for (int i=1; i<=100;i++)


{
[Link](“”+i);
[Link](150);
}
}
catch (Exception ex)
{
[Link]();
}
}
public static void main(String[] args)
{
new ThreadClass().show();
}
}

Copyright © 2023 [Link] [SYB.B.A(C.A)]


All Rights Reserved.
30

Common questions

Powered by AI

Synchronization in Java ensures that multiple threads do not execute certain critical section codes simultaneously. By using synchronized blocks or methods, only one thread can hold the lock of an object at any time, preventing other threads from accessing shared resources in ways that might lead to data corruption . For instance, if multiple threads attempt to write to a shared file without synchronization, data may be overridden. Synchronization ensures one thread completes its action before another gains access, maintaining data integrity .

Extending the Thread class is simpler as it directly provides the start() and run() methods to launch and define the task of the thread, respectively . However, it limits the class from inheriting from any other class (Java does not allow multiple inheritance). On the other hand, implementing the Runnable interface allows for greater flexibility, as a class can still extend another class while being eligible for multithreading. Runnable promises a more organized structure by defining the run() method, thus promoting a clearer separation of code related to business logic and threading .

The wait(), notify(), and notifyAll() methods enable inter-thread communication, allowing threads to cooperate while executing synchronized blocks. The wait() method makes a thread release its lock and enter a waiting state until another thread calls notify() or notifyAll() for the same object . notify() wakes a single waiting thread, while notifyAll() wakes all threads waiting on the object's monitor . These methods must be called within a synchronized context since they manipulate the locks and states associated with an object's monitor, ensuring concurrency safety and preventing race conditions .

The sleep() method pauses a thread for a specified time without releasing the lock that the thread holds, which means it simply delays execution and resumes automatically after the time expires . It is a static method of the Thread class. Conversely, the wait() method relinquishes the lock on the object so that other synchronized threads can access it and requires notify() or notifyAll() (or timeout) to resume execution . Unlike sleep, wait is a non-static method residing in the Object class, reflecting its association with object-level monitors .

The Thread class in Java provides several methods critical to managing thread execution, such as start(), run(), sleep(), join(), and interrupt(). The start() method initiates the thread, transitioning it to the runnable state . run() contains the actual code the thread executes . sleep() pauses the execution of the thread for a specified duration, facilitating timed waiting without consuming CPU resources . join() allows one thread to wait for the completion of another, a crucial mechanism for maintaining sequential execution when necessary . The interrupt() method signals a thread to terminate, useful for halting tasks based on application logic . These methods collectively enable precise control over thread life cycles and efficient scheduling.

Monitors in Java are used to facilitate synchronization by associating a lock with every object. This lock can only be held by one thread at a time, ensuring exclusive access to critical sections of code (synchronized methods or blocks) within that object . When a thread enters a synchronized block or method, it acquires the monitor lock; other threads attempting to enter the same block will be blocked until the lock is released . This mechanism allows Java to effectively manage thread interference and memory consistency errors, key challenges in concurrent programming .

A thread in Java begins in the 'New' state, where it is created but not yet started . Once the start() method is invoked, the thread enters the 'Runnable' state, indicating it is ready to run and may be executing . 'Waiting' is a state a thread enters when it waits for another thread to complete a task, returning to 'Runnable' upon notification . 'Timed Waiting' is similar but occurs for a specified duration or until a specific event triggers . Lastly, a thread enters the 'Dead' state after completing execution or being terminated due to external factors like system interrupts . Transitions typically involve notifying, timing, or completing tasks as governed by Java's thread scheduling mechanisms.

Thread priorities in Java can affect the order in which threads are scheduled for execution. The Java thread scheduler utilizes these priorities; threads of higher priority (higher integer values) are generally chosen to execute over lower-priority threads . The setPriority() method sets a thread’s priority, and getPriority() retrieves it . Java defines priorities as constants ranging from Thread.MIN_PRIORITY (1) to Thread.MAX_PRIORITY (10), with Thread.NORM_PRIORITY (5) as the default value . Although priorities suggest execution order, they do not guarantee it, as the actual scheduling behavior may vary by JVM implementation and platform-specific thread scheduling policies .

In Java multithreading, thread priorities influence the order of thread execution by suggesting a relative importance level to the Java Virtual Machine's (JVM) scheduler . Higher-priority threads are generally preferred over lower-priority ones when CPU resources are allocated. Thread scheduling utilizes these priorities to determine which among the runnable threads should execute, facilitating efficient CPU cycles allocation . Although priorities hint at execution preference, they are advisory, not mandates, thus actual execution may depend on other factors like JVM implementation and operating system capabilities .

The synchronized keyword in Java restricts access to methods to one thread at a time, guarding a block or a method such that multiple threads cannot concurrently execute a synchronized block within the same object . This is crucial in a multithreading context where threads often interact with shared resources that may be inconsistently updated if accessed simultaneously . By ensuring that only one thread can execute a synchronized method or block at any point, synchronization prevents data inconsistencies and race conditions, thereby preserving the integrity and predictability of concurrent processing .

You might also like