Unit-4 : Multi Threading
Thread Life Cycle
The life cycle of a thread in Java is controlled by JVM.
During the execution of thread, it is in any of the following five states.
Hence Java thread life cycle is defined in five states.
i. New: The thread is in new state when the instance of thread class is created but before the calling of start() method.
ii. Runnable: The thread is in runnable state after the invocation start() method, but the thread scheduler has not selected it to be the running thread. Any number of threads exists in this state.
iii. Running: The thread is in running state when the thread scheduler selects a thread for execution.
iv. Waiting/blocked/sleeping: this is the state when the thread is still alive but is not eligible currently to run.
v. Terminated: A thread is in terminated or dead state when its run() method exits.
II)Explain any 6 methods of Thread class:
1. public void start():
starts the execution of the thread. start() method of Thread class is used to start a newly created thread.
It performs following tasks:
1. A new thread starts
2. The thread moves from New state to the Runnable state.
3. When the thread gets a chance to execute, its target run() method will be called and executes.
2. public void run(): It is the entry point of a thread , used to perform action for a thread.
3. public int getPriority(): It returns the priority of the thread.
4. public int setPriority(int priority): It is used to set or change the priority of the thread.
5. public String getName(): It returns the name of the thread.
6. public void setName(String name): It is used to set or change the name of the thread.
III)Creating Thread by extending Thread Class
or
5) Explain the program for concurrent execution of multiple threads. or
6) Write program on Thread Priorities
or
Create a multithreaded java program by creating a subclass of Thread and then creating, initializing, and staring two Thread objects from your class. The threads will execute concurrently and display “Java is object oriented” in console window.
class NewThread extends Thread{
NewThread(String name){
super(name);
}
public void run(){
try {
for(int i=1;i<=4;i++ ) {
System.out.println("Java is object oriented" + getName());
sleep(1000);
}
}
catch (InterruptedException ie) {
System.out.println("Child Thread - Exception caught");
}
}
}
public class ThreadDemo{
public static void main(String args[]){
NewThread t1 = new NewThread("First");
NewThread t2 = new NewThread("Second");
NewThread t3 = new NewThread("Three");
t1.setPriority(Thread.MIN_PRIORITY);
t2.setPriority(Thread.MAX_PRIORITY);
t3.setPriority(5);
t1.start();
t2.start();
T3.start();
System.out.println("Main Program");
}
}
IV)Write or explain Creating Thread – Implementing Runnable Interface
class MyRunnable implements Runnable
{
public void run()
{
for(int i=0;i<5;i++)
{ System.out.println("Child Thread");
}
}
}
class ThreadDemo
{
public static void main(String[] args)
{
MyRunnable r=new MyRunnable();
Thread t=new Thread(r);//here r is a Target Runnable
t.start();
for(int i=0;i<5;i++)
{System.out.println("main thread");
}
}
}
Synchronizing Threads
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.
Synchronization can be of two forms
1)Mutual Exclusion
2)Inter Thread communication
1. Mutual Exclusion
Keeps threads away from interfering with one another while sharing data. Allows only one thread to access shared data.
Mutual exclusive threads can be implemented using
i) Synchronized Method ii) Synchronized Block
i)Synchronized method is used to lock an object for any shared resource.
//program
class Table {
synchronized void printTable(int n) {
for (int i = 1; i <= 5; i++) {
System.out.println(n * i);
}
}
}
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;
}
public void run() {
t.printTable(10);
}
}
public class TestSync {
public static void main(String[] args) {
Table obj = new Table();
MyThread1 t1 = new MyThread1(obj);
MyThread2 t2 = new MyThread2(obj);
t1.start();
t2.start();
}
}
Synchronized block can be used to perform synchronization on any specific resource of a method.
Explain about Interthread communication / communication between threads.
Interthread communication is a mechanism in which a thread is paused running in its critical section (synchronized block) and another thread is allowed to enter into the same section.
Eg: Producer-Consumer Problem.
Java Provides Interthread communication by using three methods of Object class.
wait() :Makes the current thread wait until another thread notifies it.
notify() :Wakes up a single waiting thread.
notifyAll() :Wakes up all waiting threads.
//Producer-Consumer problem ---> Inter Thread Communication.
class Buffer
{
int item;
boolean produced = false;
synchronized void produce(int x)
{
if(produced)
{
try{
wait();
}
catch(InterruptedException ie)
{
System.out.println("Exception Caught");
}
}
item =x;
System.out.println("Producer - Produced-->" +item);
produced =true;
notify();
}
synchronized int consume()
{
if(!produced)
{
try{
wait();
}
catch(InterruptedException ie)
{
System.out.println("Exception Caught " +ie);
}
}
System.out.println("Consumer - Consumed " +item);
produced = false;
notify();
return item;
}
}
class Producer extends Thread
{
Buffer b;
Producer( Buffer b)
{
this.b = b;
start();
}
public void run()
{
b.produce(10);
b.produce(20);
b.produce(30);
b.produce(40);
b.produce(50);
}
}
class Consumer extends Thread
{
Buffer b;
Consumer(Buffer b)
{
this.b = b;
start();
}
public void run()
{
b.consume();
b.consume();
b.consume();
b.consume();
}
}
public class PCDemo
{
public static void main(String args[])
{
Buffer b = new Buffer(); //Synchronized Object
Producer p = new Producer(b);
Consumer c = new Consumer(b);
}
}

Comments
Post a Comment