UNIT 2 - Multithreading
UNIT 2 - Multithreading
UNIT 2 - Multithreading
UNIT 2: MULTITHREADING
1. Threading Basics
Multithreading in Java is a process of executing multiple threads
simultaneously.
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.
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
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
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
3. Creating Threads
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 ();
}
}
6
UNIT 2: MULTITHREADING
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.
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.
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
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 {
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
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
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.
20
UNIT 2: MULTITHREADING
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
atoz t = new atoz();
t.start();
}
}
21
UNIT 2: MULTITHREADING
import java.util.Arrays;
import java.util.List;
22
UNIT 2: MULTITHREADING
23
UNIT 2: MULTITHREADING
import java.awt.Label;
import javax.swing.JFrame;
{
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();
}
}
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
{
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