Multithreading Programming:: Unit 3: Multithreading and Event Handling
Multithreading Programming:: Unit 3: Multithreading and Event Handling
1. Multithreading programming :
Multithreading is a conceptual programming paradigm where a program is divided into
two or more subprogram, Which can be implemented at the same time in parallel.
This is something similar to dividing a task into subtask and assigning them to processor
for execution independently and simultaneously.
Multithreading is a specialized form of multitasking. In process-based multitasking, a
program is the smallest unit of code that can be dispatched by the scheduler.
In a thread-based multitasking environment, the thread is the smallest unit of dispatch
able code. This means that a single program can perform two or more tasks
simultaneously.
2 .Thread:
Thread can enter into different state during life of thread, different stages in thread are as
follows:
New born
Runnable
Running
Dead
Blocked
When we create the thread class object, then thread is said to be born and move to new
born state. But still thread is not under running state.
Thread can be moved to either one of two state as follows:
Thread can move from born state to dead state when we invoke stop() method.
Thread can move from born state to runnable state when we invoke start() method.
Runnable state:
Runnable state means thread is ready for execution and waiting for the processor to free.
All thread are joined in queue and waiting for execution.
If all the threads have equal priority,Then they are given atime slot for execution in round
robin fashion ie. FCFS fashion.
Running state means, Thread is under execution. Thread will run until its relinquish control on
its own or its is preempted by the higher priority thread.
Blocked state:
Thread is said to be blocked when it is preempted from entering into runnable state and
subsequently the running state.
This can be happen when thread is suspend, wait, sleep in order to satisfy certain
requirements.
Dead State:
Thread can be killing as soon as its born state by calling stop() method.
Thread will automatically kill, as soon as its completed the operation
3.Creating thread:
Runnable interface declare the run() method that is required for implementing thread in
our program. The following are the steps are taken to implement the runnable interface.
Declare the class by implementing Runnable interface
Implement the run() method.
Crteate a thred by defining an object that is instantiated from this Runnabel class as the
target of that thread
Call the start() method to run the thread.
Syntex:
class Class_Name implements Runnable
{
public void run()
{
/* Implements operation */
}
public static void main(String ar[])
Program:
class A implements Runnable
{
public void run()
{
for(int i=0;i<10;i++)
System.out.println(“Class A=”+i);
}
}
class B implements Runnable
{
public void run()
{
for(int i=0;i<10;i++)
System.out.println(“class B=”+i);
}
public static void main(String ar[])
{
A a1=new A();
B b1=new B();
Thread t1=new Thread(a1);
Thread t2=new Thread(b1);
t1.start();
t2.start();
}
}
5. Threads methods:
Yield(),stop(),suspend(),resume(),wait(),notify(),notifyall().
1.yield()
Calling yield() will move the current thread from running to runnable, to give other threads a
chance to execute. However the scheduler may still bring the same thread back to running when
processor is free.
Stop():
When stop() is called then processor will kill thread permentally.It means thread move to
dead state.
class A extends Thread
{
class B
{
public static void main(String ar[])
{
A a1=new A();
a1.start();
}
}
Suspend():
When suspend() is called then processor Sends the calling thread into block state.
Using resume() method its bring the thread back from block state to running state.
Thread Priority:
Each thread assigned a priority,which effects the order in which it is scheduled for
running.
Thread of same priority are given equal treatment by the java scheduler and there for they
share the processor on FCFS basis
Java permits us to set the priority of the thread using setPriority()methods.
Final void setPriority(int level)
Where level specify the new priority setting for the calling thread. Level is the integer
constant as follows:
MAX_PRIORITY
MIN_PRIORITY
NORM_PRIORITY
The MAX_priority value is 10,MIN_PRIORITY values is 1 And NORM_PRIORITY is
the default priority whose value is 5.
We can also obtain the current priority setting value by calling getPriority() method of
thread.
Final int getPriority()
Program:
class A extends Thread
{
public void run()
{
for(int i=0;i<10;i++)
{
s.o.p(“class a thread=”+i);
}
}
}
class B extends Thread
{
Dept of CSE,CEC java & J2EE(10cs753) Page 8
public void run()
{
for(int i=0;i<10;i++)
{
s.o.p(“Class b thread=”+i);
}
}
class MainThread
{
public static void main(String ar[])
{
A a1=new A();
B b1=new B();
a1.setPriority(Thread.MAX_PRIORITY);
b1.setPriority(Thread.MIN_PRIORITY);
a1.start();
b1.start();
b1.setPriority(a1.getPriority()+10);
}
}
Synchronization:
When two or more thread needs access to the 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 synchronized is the concepts of monitor or semaphores. A monitor is an object
that is used as mutually exclusive lock or mutex. Only one thread can own a monitor at a
given time. When one thread acquires a lock it is said to have entered the monitor.
All other thread attempting to enter the locked monitor will be suspended until the first
thread exits the monitor. These other thread are said to be waiting for monitor.
This can be achieved by using keyword synchronized to method.
Syntex:
synchronized void method_name()
{ /* implementation or operation
}
Program:
class A
{
Inter-thread communication:
Inter-thread communication can be defined as exchange of message between two or more
threads. The transfer of message takes place before or after changes of state of thread.
The inter-thread communication can be achieved with the help of three methods as
follows:
Wait(),notify() notifyall()
Program:
class A
{
int stack[]=new int[10];
int top=-1;
Synchronized void produce(int item)
{
if(top==10)
try
{
wait();
}
catch(Exception e)
{
System.out.println(e);
}
Satck[++top]=item;
Reader-writer problem:
Reader thread reading an item from the buffer, Where as writer thread writing an item to
buffer.
If reader is reading then writer has to wait unless and until reading is finish.
While writing thread writing an content then no other thread read the content unless and
until writing is over.
This problem can be achieved using wait, notify and nitifyall method and using
synchronized keyword to method.
Program:
Class A
{
class C
{
public static void main(String ar[])
{
A a1=new A();
B b1=new B();
a1.start();
b1.start();
System.out.println(a1.isAlive());
System.out.println(b1.isAlive());
try
{
A1.join();
B1.join();
}
catch(Exception e)
{
System.out.println(e);
}
System.out.println(“main thread dead”);
}
}