What Are Threads?

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 15

What are Threads?

• A piece of code that run in concurrent with other


threads.
• Each thread is a statically ordered sequence of
instructions.
• Threads are being extensively used express
concurrency on both single and multiprocessors
machines.
• Programming a task having multiple threads of
control – Multithreading or Multithreaded
Programming.
Java Threads
• Java has built in thread support for Multithreading
• Synchronization
• Thread Scheduling
• Inter-Thread Communication:
• currentThread start setPriority
• yield run getPriority
• sleep stop suspend
• resume

• Java Garbage Collector is a low-priority thread.


Threading Mechanisms...
• Create a class that extends the Thread class
• Create a class that implements the Runnable
interface
Extending Thread class
• Threads are implemented as objects that contains a
method called run()
class MyThread extends Thread {
public void run() {
// thread body of execution
}
}
• Create a thread:
MyThread thr1 = new MyThread();
• Start Execution of threads:
thr1.start();
• Create and Execute:
new MyThread().start();
An example
class MyThread extends Thread { // the thread
public void run() {
System.out.println(" this thread is running ... ");
}
} // end class MyThread

class ThreadEx1 { // a program that utilizes the thread


public static void main(String [] args ) {
MyThread t = new MyThread();
// due to extending the Thread class (above)
// I can call start(), and this will call
// run(). start() is a method in class Thread.
t.start();
} // end main()
} // end class ThreadEx1

5
Implementing Runnable interface
class MyThread implements Runnable{
.....
public void run() {
// thread body of execution
}
}
• Creating Object:
MyThread myObject = new MyThread();
• Creating Thread Object:
Thread thr1 = new Thread( myObject );
• Start Execution:
thr1.start();
An example
class MyThread implements Runnable {
public void run() {
System.out.println(" this thread is running ... ");
}
} // end class MyThread
class ThreadEx2 {
public static void main(String [] args ) {
Thread t = new Thread(new MyThread());
// due to implementing the Runnable
interface
// I can call start(), and this will call run().
t.start();
} // end main()
} // end class ThreadEx2 7
Life Cycle of Thread
new
wait()
start() sleep()
suspend()
blocked
runnable non-runnable

notify()
stop()
slept
resume()
dead unblocked
8
Thread Synchronisation
• Applications Access to Shared Resources need to
be coordinated.
• Printer (two person jobs cannot be printed at

the same time)


• Simultaneous operations on your bank account.

• Can the following operations be done at the

same time on the same account?


• Deposit()
• Withdraw()
• Enquire()
Shared Resources
• If one thread tries to read the data and other
thread tries to update the same date, it leads to
inconsistent state.
• This can be prevented by synchronising access to
the data.
• Use “Synchronized” method:
public synchronized void update() {

}
Thread Priority
• In Java, each thread is assigned priority, which
affects the order in which it is scheduled for
running. The threads so far had same default
priority (NORM_PRIORITY) and they are served
using FCFS policy.
• Java allows users to change priority:

• ThreadName.setPriority(intNumber)
• MIN_PRIORITY = 1

• NORM_PRIORITY=5

• MAX_PRIORITY=10
Thread Priority Example
class A extends Thread{
public void run() {
System.out.println("Thread A started");
for(int i=1;i<=4;i++) {
System.out.println("\t From ThreadA: i= "+i);
}
System.out.println("Exit from A");
}
}
class B extends Thread{
public void run() {
System.out.println("Thread B started");
for(int j=1;j<=4;j++) {
System.out.println("\t From ThreadB: j= "+j);
}
System.out.println("Exit from B");
}
}
Thread Priority Example
class C extends Thread{
public void run() {
System.out.println("Thread C started");
for(int k=1;k<=4;k++) {
System.out.println("\t From ThreadC: k= "+k);
}
System.out.println("Exit from C");
}
}
class ThreadPriority{
public static void main(String args[]) {
A threadA=new A();
B threadB=new B();
C threadC=new C();
threadC.setPriority(Thread.MAX_PRIORITY);
threadB.setPriority(threadA.getPriority()+1);
threadA.setPriority(Thread.MIN_PRIORITY);
System.out.println("Started Thread A");
threadA.start();
System.out.println("Started Thread B");
threadB.start();
System.out.println("Started Thread C");
threadC.start();
System.out.println("End of main thread"); }}
Thread Interruption
When a thread interrupts another thread:
• If the interrupted thread is blocked in wait, sleep
or join, it is made runnable and the
InterruptedException is thrown
• If the interrupted thread is executing, a flag is set
indicating that an interrupt is outstanding; there is
no immediate effect on the interrupted thread
• Instead, the called thread must periodically test to
see if it has been interrupted using the
isInterrupted or interrupted methods
• If the thread doesn’t test but attempts to blocks, it
is made runnable immediately and the
InterruptedException is thrown
Summary
• True monitor condition variables are not directly supported
by the language and have to be programmed explicitly -
Java concurrency utilities
• Communication via unprotected data is inherently unsafe
• Asynchronous thread control allows thread to affect the
progress of another without the threads agreeing in
advance as to when that interaction will occur
• There are two aspects to this: suspend and resuming a
thread (or stopping it all together), and interrupting a
thread
• The former are now deemed to be unsafe due to their
potential to cause deadlock and race conditions
• The latter is not responsive enough for real-time systems

You might also like