UNIT 2 - Multithreading

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

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
java.lang 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
java.lang 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 java.io.*;
import java lang.Thread;
class Threaddemo extends Thread{
public void run() {
System.out.println ("Creating thread");
}
public static void main (string args[]){
threaddemo th= new threaddemo ();
th.start ();
}
}

e.g) Implementing Runnable interface


import java.lang.Thread;
public class Threaddemo implements Runnable{
try{
public void run (){
System.out.println ("Running a thread");
}
}

6
UNIT 2: MULTITHREADING

public static void main (staing args []){


threaddemo th= new threaddomo ();
thread thread1= new thread (th);
thread1.start();
}
}

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 java.util.Scanner;
class mythread3 implements Runnable
{
Thread t;
public mythread3(String s){
t = new Thread(this,s);
t.start();
}
public void run() {
Scanner sc = new Scanner(System.in);
System.out.println("enter number");
int n=sc.nextInt();
for(int i=0;i<n;i++) {
System.out.println(Thread.currentThread().getName());
try {
Thread.sleep(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 java.util.*;
class vowel extends Thread{
String s1;
vowel(String s){
s1=s;
start();
}
public void run() {
System.out.println("vowels are");
for(int i=0;i<s1.length();i++) {
char ch =s1.charAt(i);

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

System.out.println("Enter string");
String str=sc.next();
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 = Thread.currentThread();
cur.setPriority(Thread.MIN_PRIORITY);
int p = cur.getPriority();
System.out.println(Thread.currentThread().getName());
System.out.println("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 = Thread.currentThread();


cur.setPriority(Thread.MAX_PRIORITY);
int p = cur.getPriority();
System.out.println(Thread.currentThread().getName());
System.out.println("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++)
{
System.out.println(n*i);
try {
Thread.sleep(400);
}
catch(Exception e)
{
System.out.println(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

m1.start();
m2.start();

}
}

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 = Thread.currentThread();
S = t.getName();
System.out.println("\n Current Thread name: "+S);
p = t.getPriority();
System.out.println("\n Current Thread Priority: "+p);
t.setName("My Thread");
S = t.getName();
System.out.println("\n Changed Name: "+S);
t.setPriority(2);
p = t.getPriority();
System.out.println("\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++) {
System.out.println(""+c);
try {
Thread.sleep(3000);
}
catch(Exception e) {
System.out.println(e);
}

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

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

import java.util.Arrays;
import java.util.List;

public class light1 implements Runnable {


public enum Color {RED, ORANGE, GREEN}
private List<Color> light = Arrays.asList(Color.GREEN, Color.ORANGE,
Color.RED);

private static volatile int counter = 0;


private int i;

private static final Object lock = new Object();

public light1(Color color) {


this.i = light.indexOf(color);
}
public void run() {
try {
synchronized(lock) {
while(true) {
while(counter % light.size() != i) lock.wait();

22
UNIT 2: MULTITHREADING

System.out.println(Thread.currentThread().getName() + "::" + light.get(counter %


light.size()));
counter++;
Thread.sleep(1000);
lock.notifyAll();
}
}
} catch(InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new Thread(new light1(light1.Color.GREEN)).start();
new Thread(new light1(light1.Color.ORANGE)).start();
new Thread(new light1(light1.Color.RED)).start();
}

23
UNIT 2: MULTITHREADING

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


frame.

import java.awt.Label;
import javax.swing.JFrame;

public class Blinktext extends JFrame implements Runnable {


Thread t;
Label l1;
int f;
JFrame frame;
public Blinktext() {
t=new Thread(this);
t.start();
setLayout(null);
l1=new Label("HELLO JAVA");
l1.setBounds(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) {
t.sleep(200);
l1.setText("");
f=1;
}
if(f==1) {
t.sleep(200);
l1.setText("Hello Java");
f=0;
}
}catch(Exception e) {
System.out.println(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()
{
System.out.println(getName()+"thread created.");
while(true)
{
System.out.println(this);
int s=(int)(math.random()*5000);
System.out.println(getName()+"is sleeping for :+s+"msec");
try{
Thread.sleep(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");
t1.start();
t2.start();
try
{
t1.join();
t2.join();
}
catch(Exception e)
{
}
System.out.println(t1.getName()+"thread dead.");
System.out.println(t2.getName()+"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 java.awt.*;
import java.awt.event.*;
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”);
txt1.setBounds(50,50,100,100);
b1.setBounds(50,170,100,30);
add(txt1);
b1.addActionListener(this);
add(b1);
setSize(400,400);
setVisible(true);
cnt=0;
addWindowListener(new WindowAdapter()
28
UNIT 2: MULTITHREADING

{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
public void actionPerformed(ActionEvent ae)
{
String str;
str=ae.getActionCommand();
if (str.equals(“Start”))
{
t1.start();
}
else if (str.equals(“Stop”))
{
t1.stop();
}
}
public void run()
{
try
{
29
UNIT 2: MULTITHREADING

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


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

Copyright © 2023 Tejas.R.Shinde [SYB.B.A(C.A)]


All Rights Reserved.
30

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy