Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
21 views

Java Multithreading

Uploaded by

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

Java Multithreading

Uploaded by

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

Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-48
Topic: Chapter-8 Multithreading

 Multithreaded program extend the idea of multi-tasking, where individual


program appears to do multiple task at the same time. Each task is usually
called a thread.

 Programs that can run more than one thread at once are said to be multi-
threaded program.

 In most of our computer we have only a single processor and therefore in


reality the program is doing only one thing at a time but the processor
switches between the thread so fast that it appear to human beings that
all of them are being done simultaneously.

 A thread is similar to a program that has a single flow of control. It has a


beginning, ending and executes command sequentially.

 The structure of multi-threaded program is shown in the following figure.

Main
Thread

Thread Thread Thread


Switching Switching
A B C

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Creating Thread
Thread can be created by following two ways
1. By extending Thread class.
2. By implementing Runnable Interface

1. Creating a thread by extending Thread class :


It includes following steps
a) Declare the subclass of Thread class.

b) Override the run() method, which is responsible for executing the


sequence of code that the thread will execute.

c) Create a Thread object and call the start() method to initiate thread
execution.

Write a program to create thread by extending Thread class.


class A extends Thread
{
public void run()
{
for(int i=1;i<=30;i++)
System.out.println("A Thread : i = "+i);

System.out.println("Exiting A Thread");
}
}
class B extends Thread
{
public void run()
{
for(int j=1;j<=30;j++)
System.out.println("B Thread : j = "+j);

System.out.println("Exiting B Thread");
}

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

class C extends Thread


{
public void run()
{
for(int k=1;k<=30;k++)
System.out.println("C Thread : k = "+k);

System.out.println("Exiting C Thread");
}
}

class ThreadTest
{
public static void main(String [] args)
{
A a = new A();
B b = new B();
C c = new C();

a.start();
b.start();
c.start();
}
}
Output:

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-49
Topic: Thread Life Cycle OR Thread States
Thread states/Thread life cycle is very basic question, before going deep
into concepts we must understand Thread life cycle.

Thread have following states


 New
 Runnable
 Running
 Waiting/blocked/sleeping
 Terminated (Dead)

Thread states in diagram

start()

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Thread states in detail

1. New State
When you create object of Thread with the new operator that means it
is in the born state, it does not start executing code inside the thread. It
remains in this state until we call the start () method.

2. Runnable State
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 State
The thread is in running state, if the thread scheduler has selected it for
running.

4. Waiting or Blocked State


This is the state when the thread is still alive, but currently not eligible to run.
A thread enters in the blocked state when one of the following actions occurs.
(a) When we call sleep() method of the thread.
(b) The thread calls an operation that is blocking an input/ output.
(c) The thread calls the wait method.
(d) The thread tries to lock an object that is currently locked by
other thread.
Moving out of Block State :
(a) When the specified no. of milliseconds is complete.
(b) When the input/ output operation is complete.
(c) When the other thread call notify() or notifyall() method.
(d) When the other thread release the ownership of the lock.

5. Dead State:
A thread is considered dead when its run() method completes.

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-50
Topic: Thread Constructors and Its Methods

Constructors
Thread()
Allocates a new Thread object.
Thread(Runnable target)
Allocates a new Thread object.
Thread(Runnable target, String name)
Allocates a new Thread object with specified
name.
Thread(String name)
Allocates a new Thread object with specified
name.

Methods of Thread Class:


static Thread currentThread()
Returns a reference to the currently executing thread
object.
String getName()
Returns this thread's name.
int getPriority()
Returns this thread's priority.
boolean isAlive()
Tests if this thread is alive.
void join()
Waits for this thread to die.
void run()
If this thread was constructed using a
separate Runnable run object, then
that Runnable object's run method is called; otherwise,
this method does nothing and returns.

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

void setName(String name)


Changes the name of this thread to be equal to the
argument name.
static void sleep(long millis) throws Exception
Causes the currently executing thread to sleep
(temporarily cease execution) for the specified number of
milliseconds, subject to the precision and accuracy of
system timers and schedulers.
void start()
Causes this thread to begin execution; the Java Virtual
Machine calls the run method of this thread.
void setPriority(int newPriority)
Changes the priority of this thread.

Java Thread Priorities:-


 Every thread have priority. Java assign priority to every thread that
determine how that thread should be treated with respect to other.
 The thread priority is an integer value from 1 to 10. Where 1 is the
minimum priority and 10 is the maximum priority.
 When more than one threads are running higher priority thread get
preference over threads with lower priority.
 The default priority of the thread will be 5.
 To set a thread’s priority call setPriority( ) method. The setPriority( )
method require one argument of type int. And the getPriority( ) method
returns the priority of the thread.
 The thread class also contain three constants which are
MAX_PRIORITY
MIN_PRIORITY
NORM_PRIORITY
These constants specify minimum, maximum and default priority.

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-51
Topic: Thread Synchronization

Synchronization:- (Object lock)


 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. 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.

Understanding the problem without Synchronization


In this example, there is no synchronization, so output is inconsistent. Let's see
the example:

class Table {

void printTable(int n) { //method not synchronized

System.out.println("Multiplication Table of "+n+ " is");


for(int i=1;i<=5;i++){
System.out.println(n+" X "+i+" = "+n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
System.out.println("---------------------------------------------------");
}
}

class MyThread1 extends Thread {

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Table t;
MyThread1(Table t) {
this.t=t;
}

public void run(){


t.printTable(5);
}
}
class MyThread2 extends Thread {
Table t;
MyThread2(Table t){
this.t=t;
}

public void run(){


t.printTable(7);
}
}
class SysnTest {
public static void main(String args[]) {
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}

Output:

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

There are two ways that you can synchronize your code.
1) Using synchronize 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.

Example of synchronized method:


class Table {
synchronized void printTable(int n) {

System.out.println("Multiplication Table of "+n+ " is");


for(int i=1;i<=5;i++) {
System.out.println(n+" X "+i+" = "+n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
System.out.println("---------------------------------------------------");
}
}
class MyThread1 extends Thread {
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}
}
class MyThread2 extends Thread {
Table t;
MyThread2(Table t){
this.t=t;
}

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

public void run(){


t.printTable(7);
}
}

class SysnTest {
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Output:

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

2) The synchronized statement:-


 While creating synchronized methods within classes that you create is an
easy and effective means of achieving synchronization. It will not work in all
cases.

 Imagine that you want to synchronize access to objects of a class that was
not designed for multithreaded access. That is the class does not use
synchronized methods. Further, this class was not created by you, but by a
third party and you do not have access to the source code. Thus it is not
possible for you to add synchronized to the appropriate methods within the
class. In this situation, you simply put calls to the methods defined by this
class inside a synchronized block.

 The general form is


synchronized (object)
{
// statement to be synchronized
}

 Here, object is a reference to the object being synchronized. Here is an


alternative of the preceding example. It uses a synchronized block within
the run( ) method.
public void run( )
{
synchronized(t) {
t.printTable(5);
}
}

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260

You might also like