Content-Length: 3120497 | pFad | https://www.scribd.com/document/796789057/Multi-Threading-Notes
2Multi Threading Notes
Multi Threading Notes
Multi Threading Notes
Multitasking
Executing multiple tasks simultaneously.
Each task consists of cpu bound instructions and I/O bound instructions.
During I/O instruction execution, the cpu(processor) will be idle.
Multi tasking utilizes this time by assigning others tasks to the processor.
By making processor busy, the throughput (number of jobs that can be completed in
unit time) can be increased.
OS will use different cpu scheduling algorithms to share processor time among
multiple tasks.
A task can be atleast a program. We cant further subdivide.
Advantages
Reduces idle time of the cpu (increase throughput)
Quick response time.
Multithreading
Specialized form of multitasking.
Each task can be a thread.
A program can consists of two or more threads that can run concurrently.
Each thread defines a separate path of execution.
Threads are light weight, they share the same address space.
Context switching is easier.
Java provides built in support for multithreading.
In java the execution of main method itself is a thread created automatically when the
program started.
Creating a thread
We can create a new thread in two ways
1. by extending Thread class.
2. by implementing Runnable interface.
sleep()
Syntax: sleep(long millisec);
Static method
Makes the current thread to suspend its execution for specified millis secods.
If the thread is interrupted before the sleep time expires, it throws
InterruptedException.
class demo1
{
public static void main(String args[])
{
MyThread m=new MyThread();
m.start();
for(int i=0;i<10;i++)
{
System.out.println("Main Thread:"+i);
}
}
}
class demo4
{
public static void main(String args[])
{
FifthTable f=new FifthTable();
SixthTable s=new SixthTable();
f.start();
s.start();
}
}
Thread priorities
An integer value that specify relative priority of one thread to another.
Among the threads of equal priority, JRE (Thread shedular) may schedule threads in
any order for execution.
Methods:
setPriority(int priority)
int getPriority()
Priority value ranges from 0(low) to 10(high).
Normal priority is 5.
These are represeted by final static variables in Thread class
Thread.MIN_PRIORITY
Thread.MAX_PRIORITY
Thread.NORM_PRIORITY
Thread schedular may give preference to high priority threads while scheduling
threads for execution.
Thread priorities are only to influence the thread schedular.
Can't rely on them.
for(int i=0;i<10;i++)
System.out.print("\nchild thread "+i);
}
System.out.println(Thread.currentThread().getPriority());
for(int i=0;i<1000;i++)
System.out.print("\nMain thread "+i);
}
}
Context switching
A thread can voluntarily relinquish control.
A thread can be preempted by a higher priority thread.
yield()
Pauses the currently executing thread temporarily for giving a chance to the
remaining threads of the same priority to execute.
If there is no waiting thread or all other waiting threads have a lower priority then the
same thread will continue its execution.
The yielded thread when it will get the chance for execution is decided by the thread
scheduler.
class demo7
{
public static void main(String args[])
{
MyThread m=new MyThread();
m.start();
for(int i=0;i<100;i++)
{
System.out.println("Main Thread "+i);
}
}
}
isAlive() : helps us to know whether the thread has finished its execution or not.
join() : makes the the caller thread to wait until the thread on which join() has
invoked completes it execution.
synchronization
Wihen two or more threads needs 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.
Monitor
How to synchronize
Method synchronization
Whichever the methods of the resource(object) you want to synchronize, decalare
those methods with synchronized modifier.
All objects have implicit monitor.
To enter an objects monitor, just call any synchronized method.
Note:
While a thread is inside a synchronized method, all other threads that try to call it (or
any other synchronized method) on the same object have to wait.
class Display
{
public void wish(String name)
{
for(int i=0;i<10;i++)
{
System.out.print("Good morning");
try
{
Thread.sleep(2000);
}
catch(InterruptedException e)
{
}
System.out.println(name);
}
}
}
class Mythread extends Thread
{
Display d;
String name;
Mythread(Display d,String name)
{
this.d=d;
this.name=name;
}
class Display
{
public synchronized void wish(String name)
{
for(int i=0;i<10;i++)
{
System.out.print("Good morning : ");
try
{
Thread.sleep(2000);
}
catch(InterruptedException e)
{
}
System.out.print(name);
System.out.println();
}
}
}
class Mythread extends Thread
{
Display d;
String name;
Mythread(Display d,String name)
{
this.d=d;
this.name=name;
}
Synchronized block
If you want to synchronize access to objects of a class that was not designed for
multithreaded access (that is the class does not use snchronzed methods).
If the class was created by a third party, we do not have access to the code.
Then we can acquire lock on the object with synchronized block.
syntax
synchronized(target_instance)
{
target_instance.method1();
}
Example_Program : Synchronized block example.
class Display
{
public void wish(String name)
{
synchronized(this)
{
for(int i=0;i<10;i++)
{
System.out.print("Good morning : ");
try
{
Thread.sleep(2000);
}
catch(InterruptedException e)
{
}
System.out.print(name);
System.out.println();
}
}
}
}
Note:
Static and non static synchronized methods will not block each other (ie they can run
at the same time from different threads since they acquire lock on different things).
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.
wakes up all the threads that are waiting on this object's monitor.
One of the thread will be granted access by the Thread Schedular.
These three methods are not from Thread class, these are from Object class.
Note:
1) There exists a very rare possibility that the waiting thread resumes without
notify(). (for no apparent reason)
Oracle recommends that calls to wait() should take place with in a loop that checks
the condition on which the thread is waiting.
2) IllegalMonitorStateException
Thrown to indicate that a thread has attempted to wait on an object's monitor Or to
notify other threads waiting on an object's monitor without owning the specified
monitor.
3) You must call the wait(), notify() or notifyAll() from a synchronized context.
class Buffer
{
int a;
boolean produced = false;
if(produced)
{
System.out.println("Producer is waiting...");
try{
wait();
}catch(Exception e){
System.out.println(e);
}
}
a=x;
System.out.println("Product" + a + " is produced.");
produced = true;
notify();
}
Fetched URL: https://www.scribd.com/document/796789057/Multi-Threading-Notes
Alternative Proxies: