Module5 Jjj
Module5 Jjj
Module5 Jjj
Email: nanditab.rvitm@rvei.edu.in
syedaayesha.rvitm@rvei.edu.in
RV Institute of Technology and Management ®
Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking
toutilize the CPU. Multitasking can be achieved by two ways:
• Each process has its own address in memory i.e. each process allocates separate
memory area.
• Process is heavyweight.
• Cost of communication between the processes is high.
• Switching from one process to another require some time for saving and loading
registers, memory maps, updating lists etc.
• Less efficient
An instance of Thread class is just an object, like any other object in java. But a thread of
execution means an individual "lightweight" process that has its own call stack. In java each
thread has its own call stack as shown in Fig. 5.2.
• Often, it must be the last thread to finish execution because it performs various shutdown
actions.
The life cycle of the thread is shown in Fig. 5.3 in java is controlled by JVM. The java thread
states are as follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
1. New:
The thread is in new state if you create an instance of Thread class but
before the invocation ofstart () method.
2. Runnable:
When we call start () function on Thread object, its state is changed to Runnable.
The control is given to Thread scheduler to finish its execution. Whether to run this
thread instantly or keep it in runnable thread pool before running, depends on the
OS implementation of thread scheduler.
a) Running:
When thread is executing, it’s state is changed to Running. Thread scheduler picks one
of the thread from the runnable thread pool and change its state to Running. Then CPU
starts executingthis thread. A thread can change state to Runnable, Dead or Blocked
from running state depends on time slicing, thread completion of run() method or
waiting for some resources.
b) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run. Waiting
− Sometimes, a thread transitions to the waiting state while the thread waits for another
thread to perform a task. A thread transitions back to the runnable state, only when
another thread signals the waiting thread to continue its execution.
c) Terminated
Thread Creation
When the thread starts it schedules the time slots for several sub threads and the JVM scheduler
schedules the time slot to every thread based on round robin technique or priority based.
Method Description
String getName() Retrieves the name of running thread in the current context in String
format
void start() This method will start a new thread of execution by calling run() method
of Thread/runnable object.
void run() This method is the entry point of the thread. Execution of thread starts
from this method.
void sleep(int This method suspends the thread for mentioned time duration in
argument
sleeptime) (sleeptime in ms)
void yield() By invoking this method, the current thread pauses its execution
temporarily and allow other threads to execute.
void join() This method used to queue up a thread in execution. Once called on
thread, current thread will wait till calling thread completes its
execution
• run () method introduces a concurrent thread into your program. This thread will end
whenrun() returns.
• You must specify the code for your thread inside run() method.
• run() method can call other methods, can use other classes and declare variables just
like anyother normal method.
After you create a class that implements Runnable, you will instantiate an object of type
Thread from within that class. Thread defines several constructors. The one that we will use
is shown here:
Syntax :
Thread(Runnable threadOb, String threadName);
In this constructor, threadOb is an instance of a class that implements the Runnable interface.
This defines where execution of the thread will begin. The name of the new thread is
specified by threadName.
{
MyThread mt = new MyThread();
Thread t = new Thread(mt); t.start();
}
package applet1;
import java.io.*;
import java.util.*;
public void
run() {try {
} catch (InterruptedException e) {
System.out.println("Interrupted")
;
System.out.println(" exiting.");
}
}
class multithread {
Output: 5
15
14
4
13
3
12
2
11
exiting
exiting
Notice the call to sleep (10000) in main (). This causes threads B and A to sleep for ten
secondsand ensures that it will finish last.
Note: Write a java application program for generating 3 threads to perform thefollowing
operations.
i) Reading n numbers ii) Printing prime numbers iii) Computing average of nnumbers
The isAlive() method returns true if the thread upon which it is called is still running
otherwise itreturns false.
{
System.out.println("r1 ");
try {
Thread.sleep(500);
}
catch(InterruptedException ie)
{ }System.out.println("r2 ");
}
public static void main(String[] args)
t1.start();
t2.start();
System.out.println(t1.isAlive());
System.out.println(t2.isAlive());
}
}
Output:
r1
true
true
r1
r2
r2
But, join() method is used more commonly than isAlive(). This method waits until the thread
onwhich it is called terminates
Using join() method, we tell our thread to wait until the specified thread completes its
execution. There are overloaded versions of join() method, which allows us to specify time for
which you want to wait for the specified thread to terminate
System.out.println("r1 ");
try {
Thread.sleep(500);
}catch(InterruptedException ie){ }
System.out.println("r2 ");
}catch(InterruptedException ie){}
t2.start();
}
}
Output:
r1
r2
r1
r2
In this above program join() method on thread t1 ensures that t1 finishes it process before
threadt2 starts.
t1.join(1500);
Synchronization
At times when more than one thread try to access a shared resource, we need to ensure that
resource will be used by only one thread at a time. The process by which this is achieved is
called synchronization. The synchronization keyword in java creates a block of code referred
toas critical section.
General Syntax :
synchronized (object)
//statement to be synchronized
}
class Table{
void display(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);
}
}
}
}//end of the method
this.t=t;
}
public void run(){
t.display(100);
}
}
A t1=new A(obj);
B t2=new B(obj);
t1.start();
t2.start();
}
}
Output:
5
10
15
20
25
100
200
300
400
500
class Table{
synchronized void display(int n)
{
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try{
Thread.sleep(400);
}
catch(Exception e){
System.out.println(e);
}
}
}
}//end of the method
this.t=t;
}
t.display(100);
}
}
B t2=new B(obj);
t1.start();
t2.start();
}
}
Output:
5
10
15
20
25
100
200
300
400
• At the same time, the consumer is consuming the data (i.e. removing it from the
buffer), one piece at a time.
Solution:
This problem can be implemented or solved by different ways in Java, classical way is
using waitand notify method to communicate between Producer and Consumer thread and
blocking each of themon individual condition like full queue and empty queue.
wait ( ) tells the calling thread to give up the monitor and go to sleep until some other
threadenters the same monitor and calls notify( ) or notifyAll( ).
public class
ProducerConsumerTest
{ public static void
main(String[] args) {
Myclass c = new Myclass();
Producer p1 = new Producer(c, 1);
Consumer c1 = new Consumer(c, 1);
p1.start();
c1.start();
}
}
class Myclass {
private int contents;
private boolean available = false;
available = false;
notifyAll();
return contents;
}
wait();
} catch (InterruptedException e) { }
}
contents = value;
available = true;
notifyAll();
this.number = number;
}
public void run() {
Output:
Producer #1 put: 0
Consumer #1 got: 0
Producer #1 put: 1
Consumer #1 got: 1
Producer #1 put: 2
Consumer #1 got: 2
Producer #1 put: 3
Consumer #1 got: 3
Producer #1 put: 4
Consumer #1 got: 4
Producer #1 put: 5
Consumer #1 got: 5
Producer #1 put: 6
Consumer #1 got: 6
Producer #1 put: 7
Consumer #1 got: 7
Producer #1 put: 8
Consumer #1 got: 8
Producer #1 put: 9
Consumer #1 got: 9
Problem Statement:
There is a buffer of n slots and each slot is capable of storing one unit of data. There are
two processes running, namely, producer and consumer, which are operating on the buffer.
A producer tries to insert data into an empty slot of the buffer. A consumer tries to remove
data from a filled slot in the buffer. As you might have guessed by now, those two processes
won’t produce the expected output if they are being executed concurrently.
There needs to be a way to make the producer and consumer work in an independent manner.
import java.io.*;
import java.util.*;
class Buffer
{
private final int MaxBuffSize;
private int[] store;
private int BufferStart, BufferEnd, BufferSize;
public Buffer(int size)
{
MaxBuffSize = size;
BufferEnd = -1;
BufferStart = 0;
BufferSize = 0;
store = new int[MaxBuffSize];
}
public synchronized void insert(int ch)
{
try
{
}
}
class boundedbuffer {
public static void main(String[] args) {
System.out.println("program starting");
Buffer buffer = new Buffer(5); // buffer has size 5
Producer prod = new Producer(buffer); Consumer
cons = new Consumer(buffer);
prod.start();
cons.interrupt();
try {
prod.join();
cons.interrupt();
} catch (InterruptedException e) {}
System.out.println("End of Program");
}
}
Output:
0
1
2
3
4
5
6
End of Program
Problem Statement:
There is a shared resource which should be accessed by multiple processes. There are two
types of processes in this context. They are reader and writer. Any number of readers can
read from the shared resource simultaneously, but only one writer can write to the shared
resource. When awriter is writing data to the resource, no other process can access the
resource. A writer cannot write to the resource if there are non-zero number of readers
accessing the resource.
Solution:
From the above problem statement, it is evident that readers have higher priority than writer.
If a writer wants to write to the resource, it must wait until there are no readers currently
accessing that resource
Interthread Communication
o wait()
o notify()
o notifyAll()
1) 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.
2) notify() method
The notify() method wakes up a single thread that is waiting on this object's monitor. If any
threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary
and occurs at the discretion of the implementation.
III- Semester, Object Oriented Programming with JAVA Page 25 of 29
(BCS306A)
RV Institute of Technology and Management ®
Syntax:
3) notifyAll() method
Syntax:
Why wait(), notify() and notifyAll() methods are defined in Object class not Thread class?
wait() sleep()
The wait() method releases the lock. The sleep() method doesn't release the lock.
It should be notified by notify() or notifyAll() methods After the specified amount of time, sleep is completed.
Output:
going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed
The suspend() method of thread class puts the thread from running to waiting state. This method
is used if you want to stop the thread execution and start it again when a certain event occurs. This
method allows a thread to temporarily cease execution. The suspended thread can be resumed
using the resume() method.
Syntax
public final void suspend()
Example
1. public class JavaSuspendExp extends Thread
2. {
3. public void run()
4. {
5. for(int i=1; i<5; i++)
6. {
7. try
8. {
9. // thread to sleep for 500 milliseconds
10. sleep(500);
11. System.out.println(Thread.currentThread().getName());
12. }catch(InterruptedException e){System.out.println(e);}
13. System.out.println(i);
14. }
15. }
16. public static void main(String args[])
17. {
18. // creating three threads
19. JavaSuspendExp t1=new JavaSuspendExp ();
20. JavaSuspendExp t2=new JavaSuspendExp ();
21. JavaSuspendExp t3=new JavaSuspendExp ();
22. // call run() method
23. t1.start();
24. t2.start();
25. // suspend t2 thread
26. t2.suspend();
27. // call run() method
28. t3.start();
29. }
30. }
Output
Thread-0
1
Thread-2
1
Thread-0
2
Thread-2
2
Thread-0
3
Thread-2
3
Thread-0
4
Thread-2
4