Content-Length: 3027333 | pFad | https://www.scribd.com/document/681710912/Multi-Threading

2 Multi Threading | PDF | Computers
0% found this document useful (0 votes)
53 views17 pages

Multi Threading

Download as docx, pdf, or txt
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 17

Multithreading

Multithreading is a Java feature that allows concurrent execution of two


or more parts of a program for maximum utilization of CPU. Each part of such
program is called a thread. So, threads are light-weight processes within a
process.

Threads are light weight process because they utilize minimum resources
of the system. This means they takes less memory and less processor time.

Threads can be used to perform multiple activities concurrently in the


same program.

Types Of Threads In Java

There are two types of Threads in java.


1) User Thread
2) Daemon Thread

1) User Thread :User threads are threads which are created by the application
or user. They are high priority threads. JVM (Java Virtual Machine) will not exit
until all user threads finish their execution. JVM wait for these threads to
finish their task. These threads are foreground threads.

2) Daemon Thread :Daemon threads are low-priority threads created by


JVM, whose only role is to provide services to user threads. These threads
always run in background. These threads are used to perform some
background tasks like garbage collection and house-keeping tasks.JVM will not
wait for these threads to finish their execution. JVM will exit as soon as all
user threads finish their execution. JVM doesn’t wait for daemon threads to
finish their task.

Life Cycle of a Thread


The life cycle of the thread in java is controlled by JVM. A thread goes through various
stages in its life cycle. For example, a thread is born, started, runs, and then
dies. The java thread states are as follows:

1. New
2. Runnable
3. Running
4. Non-Runnable /Blocked/Waiting
5. Terminated/Dead
1) New:The thread is in new state if you create an instance of Thread class but
before the invocation of start() method.

2) Runnable:The thread is in runnable state after invocation of start()


method, but the thread scheduler has not selected it to be the running thread.

3) Running:The thread is in running state if the thread scheduler has


selected it.
4) Non-Runnable /Blocked/Waiting: This is the state when the thread is still
alive, but is currently not eligible to run.
5) Terminated/Dead: A thread is in terminated or dead state when its
run() method exits.

How to create thread

There are two ways to create a thread:


1. By extending Thread class
2. By implementing Runnable interface.

1).Create a Thread by Extending a Thread Class


To create a thread is to create a new class that extends Thread class
using the following two simple steps. This approach provides more flexibility
in handling multiple threads created using available methods in Thread class.

Step 1:You will need to override run( ) method available in Thread class. This
method provides an entry point for the thread and you will put your complete
business logic inside this method. Following is a simple syntax of run() method
–public void run( )
Step 2:Once Thread object is created, you can start it by calling start() method,
which executes a call to run( ) method. Following is a simple syntax of start()
method −
void start( );

Example program to create thread by extending the Thread class−

classThreadA extends Thread


{
public void run()
{
System.out.println("Running " + Thread.currentThread().getName());
for(int i = 1; i <=5; i++)
{
System.out.println(Thread.currentThread().getName()+ "=" + i);
}
System.out.println(Thread.currentThread().getName()+ " exiting.");
}
}
classThreadB extends Thread
{
public void run()
{
System.out.println("Running " + Thread.currentThread().getName());
for(int i=6; i<=10; i++)
{

System.out.println(Thread.currentThread().getName()+ "=" + i);

System.out.println(Thread.currentThread().getName() + " exiting.");

public class TestThread

public static void main(String args[])

ThreadA Th1 = new ThreadA();


Thread T1=new Thread(Th1,"thread one");

T1.start();

ThreadB Th2 = new ThreadB();

Thread T2=new Thread(Th2,"thread two");

T2.start();

Output:

Thread Methods:
Following is the list of important methods available in the Thread class.

public void start():starts the execution of the thread, then invokes the run()
method on this Thread object.

public void run():is used to perform action for a thread.

public void setName(String name): changes the name of the thread.

public String getName(): returns the name of the thread.


Public int setPriority(int priority): changes the priority of the thread.

Public int getPriority(): returns the priority of the thread.

public Thread currentThread(): returns the reference of currently executing


thread.

Public Boolean isAlive(): tests if the thread is alive.

public void suspend(): is used to suspend the thread(depricated).

public void resume(): is used to resume the suspended thread(depricated).

public void stop(): is used to stop the thread(depricated).

public void interrupt(): interrupts the thread.

Sleep(int time);

2). Thread creation by implementing the Runnable Interface

This is the another method to create thread. We create a new class which
implements java.lang.Runnable interface and override run() method. Then we
instantiate a Thread object and call start() method on this object.

Example program to create thread by implementing Runnable interface−

classThreadA implements Runnable


{
public void run()
{
System.out.println("Running " + Thread.currentThread().getName());
for(int i = 1; i <=5; i++)
{
System.out.println(Thread.currentThread().getName()+ "=" + i);
}
System.out.println(Thread.currentThread().getName()+ " exiting.");

}
classThreadB implements Runnable
{
public void run()
{
System.out.println("Running " + Thread.currentThread().getName());
for(int i=6; i<=10; i++)
{
System.out.println(Thread.currentThread().getName()+ "=" + i);
}
System.out.println(Thread.currentThread().getName() + " exiting.");
}
}

public class Testrunnable


{
public static void main(String args[])
{
ThreadA Th1 = new ThreadA();
Thread T1=new Thread(Th1,"thread one");
T1.start();
ThreadB Th2 = new ThreadB();
Thread T2=new Thread(Th2,"thread two");
T2.start();
}
}

Output:
Priority of a Thread (Thread Priority):
In a Multi threading environment, thread scheduler assigns processor to
a thread based on priority of thread. Whenever we create a thread in Java, it
always has some priority assigned to it. Priority can either be given by JVM
while creating the thread or it can be given by programmer explicitly.

Priorities are represented by a number between 1 and 10. In most cases,


thread scheduler schedules the threads according to their priority (known as
preemptive scheduling). But it is not guaranteed because it depends on JVM
specification that which scheduling it chooses.

There are 3 static variables defined in Thread class for priority.

1. public static int MIN_PRIORITY


It holds the minimum priority that can be given to a thread. The value for
this is 1.

2. public static int NORM_PRIORITY


It is the default priority that is given to a thread if it is not defined. The
value for this is 5.

3. public static int MAX_PRIORITY


It is the maximum priority that can be given to a thread. The value for
this is 10.

Get and Set methods in Thread priority:


1. public final intgetPriority()

In Java, getPriority() method is in java.lang.Thread package. it is used to


get the priority of a thread.

2. public final void setPriority(intnewPriority)

In Java setPriority(intnewPriority) method is in java.lang.Thread package.


It is used to set the priority of a thread. The setPriority() method throws
IllegalArgumentException if the value of new priority is above minimum and
maximum limit.
Example: Fetch Thread Priority

If we don’t set thread priority of a thread then by default it is set by the


JVM. In this example, we are getting thread’s default priority by using
the getPriority() method.

classMyThread extends Thread

public void run()

System.out.println("Thread Running..."+Thread.currentThread().getName());

public static void main(String[]args)

MyThread p1 = new MyThread();

MyThread p2 = new MyThread();

MyThread p3 = new MyThread();

Thread t1=new Thread(p1,"one");

Thread t2=new Thread(p2,"two");

Thread t3=new Thread(p3,"three");

t1.start();

t2.start();

t3.start();

System.out.println("t1 thread priority : " + t1.getPriority());

System.out.println("t2 thread priority : " + t2.getPriority());

System.out.println("t3 thread priority : " + t3.getPriority());

Output:
Example : Set Priority

To set priority of a thread, setPriority() method of thread class is used.


It takes an integer argument that must be between 1 and 10 OR Thread
constants (MAX_PRIORITY,NORM_PRIORITY,MIN_PRIORITY). see the below
example.

classThreadpriority extends Thread


{
public void run()
{
System.out.println("Thread Running..."+Thread.currentThread().getName());
}

public static void main(String[]args)


{
MyThread p1 = new MyThread();
MyThread p2 = new MyThread();
MyThread p3 = new MyThread();
Thread t1=new Thread(p1,"one");
Thread t2=new Thread(p2,"two");
Thread t3=new Thread(p3,"three");
t1.setPriority(2);
t2.setPriority(5);
t3.setPriority(9);
t1.start();
t2.start();
t3.start();
System.out.println("t1 thread priority : " + t1.getPriority());
System.out.println("t2 thread priority : " + t2.getPriority());
System.out.println("t3 thread priority : " + t3.getPriority());

}
}

Output:
Stopping and Blocking a thread:

Stopping a thread: Whenever we want to stop a thread from running further,


we may do so by calling its stop() method. This causes a thread to stop
immediately and move it to dead state. It forces the thread to stop abruptly
before its completion. To stop thread we use the following syntax:

t1.stop(); // t1 is thread object

Blocking a thread:A thread also can be temporarily suspended or blocked by


using either of the following methods.

t1.sleep(t);// blocked for t milliseconds


t1.suspend();// blocked until resume() method is invoked
t1.wait();//blocked until notify() method is invoked

Example program for stopping the thread:


Class UserThread implements Runnable {
private boolean exit = false;
public void run() {
while(!exit) {
System.out.println("The user thread is running");
}
System.out.println("The user thread is now stopped");
}
public void stop() {
exit = true;
}
}
public class ThreadStop {
public static void main(String args[]) throws InterruptedException {
UserThread user = new UserThread();
Thread thread = new Thread(user, "T1");
thread.start();
System.out.println(Thread.currentThread().getName() + " is stopping user
thread");
user.stop();
Thread.sleep(2000);
System.out.println(Thread.currentThread().getName() + " is finished now");
}
}
Output:
Synchronization:
What is Synchronization?

Synchronization in java is the capability to control the access of multiple threads


to any shared resource.

Java Synchronization is better option where we want to allow only one thread
to access the shared resource at a given point in time.

Why use Synchronization?

The synchronization is mainly used to

1. To prevent thread interference.


2. To prevent consistency problem.

If we do not use synchronization, and let two or more threads access a


shared resource at the same time, it will lead to distorted results.
Consider an example, Suppose we have two different threads T1 and T2, T1
starts execution and save certain values in a file temporary.txt which will be
used to calculate some result when T1 returns. Meanwhile, T2 starts and
before T1 returns, T2 change the values saved by T1 in the file temporary.txt
(temporary.txt is the shared resource). Now obviously T1 will return wrong
result.
To prevent such problems, synchronization was introduced. With
synchronization in above case, once T1 starts using temporary.txt file, this file
will be locked(LOCK mode), and no other thread will be able to access or
modify it until T1 returns.
Example with no Synchronization

In this example, we are not using synchronization and creating multiple


threads that are accessing display method and produce the random output.

class First
{
public void display(String msg)
{
System.out.print ("["+msg);
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
System.out.println ("]");
}
}

class Second extends Thread


{
String msg;
First fobj;
Second (First fp,String str)
{
fobj = fp;
msg = str;
start();
}
public void run()
{
fobj.display(msg);
}
}

public class Syncro


{
public static void main (String[] args)
{
First fnew = new First();
Second ss = new Second(fnew, "welcome");
Second ss1= new Second(fnew,"new");
Second ss2 = new Second(fnew, "programmer");
}
}
Output:

[welcome [ new [ programmer]


]
]
In the above program, object fnew of class First is shared by all the three
running threads(ss, ss1 and ss2) to call the shared method(void
display). Hence the result is nonsynchronized and such situation is
called Race condition..

There are two ways we can synchronize the threads, They


are: 1.Using Synchronized Method.
2.Using Synchronized Block.

1. Using Synchronized Method.

If you declare any method as synchronized, it is known as synchronized


method.

Synchronized method is used to lock an object for any shared resource.

When a thread invokes a synchronized method, it automatically acquires the


lock for that object and releases it when the thread completes its task.

Syntax:

synchronized return_type method_name (arguments)

Example : implementation of synchronized method

class First
{
synchronized public void display(String msg)
{
System.out.print ("["+msg);
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
System.out.println ("]");
}
}

class Second extends Thread


{
String msg;
First fobj;
Second (First fp,String str)
{
fobj = fp;
msg = str;
start();
}
public void run()
{
fobj.display(msg);
}
}

public class MyThread

public static void main (String[] args)

First fnew = new First();

Second ss = new Second(fnew, "welcome");

Second ss1= new Second(fnew,"new");

Second ss2 = new Second(fnew, "programmer");

Output:
[welcome]
[programmer]

[new]
2. Using Synchronized Block.
If want to synchronize access to an object of a class or only a part of a method
to be synchronized then we can use synchronized block for it. It is capable to
make any part of the object and method synchronized.

Example

In this example, we are using synchronized block that will make the display
method available for single thread at a time.

class First
{
public void display(String msg)
{
System.out.print ("["+msg);
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
System.out.println ("]");
}
}

class Second extends Thread


{
String msg;
First fobj;
Second (First fp,String str)
{
fobj = fp;
msg = str;
start();
}
public void run()
{
synchronized(fobj) //Synchronized block
{
fobj.display(msg);
}
}
}

public class MyThread


{
public static void main (String[] args)
{
First fnew = new First();
Second ss = new Second(fnew, "welcome");
Second ss1= new Second (fnew,"new");
Second ss2 = new Second(fnew, "programmer");
}
}

Output:

[welcome]
[new]
[programmer]

You might also like









ApplySandwichStrip

pFad - (p)hone/(F)rame/(a)nonymizer/(d)eclutterfier!      Saves Data!


--- a PPN by Garber Painting Akron. With Image Size Reduction included!

Fetched URL: https://www.scribd.com/document/681710912/Multi-Threading

Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy