Sunteți pe pagina 1din 52

What is Thread?

What is Thread?
Definition:
A thread is a single sequential flow of control within a
program.
OR
A thread is the smallest unit of processing that can be
scheduled by an operating system.
OR
A thread is a subset of the process.
It is termed as a lightweight process, since it is similar
to a real process but executes within the context of a
process and shares the same resources allotted to the
process
What Is a Thread?
A thread is like a classic program that starts at
point A and executes until it reaches point B.
Threads share the same address space and
therefore can share both data and code
Context switching between threads is usually
less expensive than between processes
Relation b/w process and thread
A thread is a subset of the process.
Process is a program in execution
Processes have their own address & process is heavy weight
process. Threads (Light weight Processes) share the address
space of the process that created it.
Process can't communicate other processes but thread do it
easily
A process may also be made up of multiple threads of execution
that execute instructions concurrently
What is MultiThreading?
A multithreaded program contains two or
more parts that can run concurrently.
Each part of such a program is called a
thread, and each thread defines a
separate path of execution.
A multithreading is a specialized form of
multitasking
Thread Architecture

Flow of Thread Program
Extend the java.lang.Thread Class.
Override the run( ) method in the subclass
from the Thread class to define the code
executed by the thread.
Create an instance of this subclass. This
subclass may call a Thread class constructor
by subclass constructor.
Invoke the start( ) method on the instance of
the class to make the thread eligible for
running.
Thread Example 1
public class A extends Thread{
public void run(){
for(int i=0; i<5; i++){
System.out.println("A class Thread : " +i);
try {
sleep(1000);
} catch (InterruptedException ex) {
System.err.println("A Interrupt");
}
}//end loop
}//end run
}//end class
Thread Example 1
public class CallThread {

public static void main(String[] args) {
A a = new A();
a.start();
}
}
Thread Example 2
class MyThread1 extends Thread{
String s=null;

MyThread1(String s1){
s=s1;
start();
}
public void run(){
System.out.println(s);
for(int i=0; i<=25; i++){
System.out.println("Thread "+i);
try {
Thread.sleep(2500);
} catch (InterruptedException e) { }
}
}
}
Thread Example 2
public class ExtendThread{
public static void main(String args[]){
MyThread1 m1=new MyThread1("Thread started....");
}
}
Thread Example 3
public class A implements Runnable{
public void run(){
for(int i=0; i<5; i++){
System.out.println("A class Thread : " +i);
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
System.err.println("A Interrupt");
}
}
}
}

Thread Example 3
public class CallThread {
public static void main(String[] args) {
A a = new A();
Thread t = new Thread(a);
t.start();
}
}
Thread program Implement Runnable
class MyThread1 implements Runnable{
Thread t;
String s=null;
MyThread1(String s1){
s=s1;
t=new Thread(this);
t.start();
}
public void run(){
System.out.println(s);
for(int i=0; i<=25; i++){
System.out.println("Thread "+i);
try {
Thread.sleep(2500);
} catch (InterruptedException e) { }
}
}
}
Thread program Implement Runnable
public class RunableThread{
public static void main(String args[]){
MyThread1 m1=new MyThread1("Thread started....");
}
}

Flow of Program
A Class implements the Runnable Interface,
override the run() method to define the code
executed by thread. An object of this class is
Runnable Object.
Create an object of Thread Class by passing a
Runnable object as argument.
Invoke the start( ) method on the instance of the
Thread class.
If you extend the Thread Class, that means that
subclass cannot extend any other Class, but if you
implement Runnable interface then you can do this.
MultiThread Program
class XThread extends Thread {
String name;
int limit;
int wait;
XThread(String name, int limit, int wait) {
this.name = name;
this.limit = limit;
this.wait = wait;
start();
}
public void run() {
System.out.println(name +" Thread start");
for(int i=0; i<=limit; i++){
System.out.println(name +" Thread "+i);
try {
sleep(wait);
} catch (InterruptedException e) { }
}
}
}//end class
MultiThread Program
public class ThreadExample {

public static void main(String[] args) {
XThread thread1 = new XThread("A",10,1000);
XThread thread2 = new XThread("B",15,1500);
XThread thread3 = new XThread("C",20,2000);
for(int i=0; i<=25; i++){
System.out.println("Main Thread "+i);
try {
Thread.sleep(2500);
} catch (InterruptedException e) { }
}
}
}
MultiThread Program Implement Runnable
class XThread implements Runnable {
String name;
int limit;
int wait;
Thread t;
XThread(String name, int limit, int wait) {
this.name = name;
this.limit = limit;
this.wait = wait;
t = new Thread(this, name +" Thread");
t.start(); // Start the thread
}
public void run() {
System.out.println(name +" Thread start");
for(int i=0; i<=limit; i++){
System.out.println(name +" Thread "+i);
try {
t.sleep(wait);
} catch (InterruptedException e) { }
}
}
}//end class
MultiThread Program Implement Runnable
public class ThreadExample {

public static void main(String[] args) {
XThread thread1 = new XThread("A",10,1000);
XThread thread2 = new XThread("B",15,1500);
XThread thread3 = new XThread("C",20,2000);
for(int i=0; i<=25; i++){
System.out.println("Main Thread "+i);
try {
Thread.sleep(2500);
} catch (InterruptedException e) { }
}
}
}
Thread Priorties
Thread Priorties
class PriorityThread extends Thread{
int count;
public void run(){
while(true){
++count;
}
}
}


Thread Priorties
class CallPriorityThread {
public static void main(String ar[])throws Exception{
PriorityThread pt1 = new PriorityThread();
PriorityThread pt2 = new PriorityThread();
PriorityThread pt3 = new PriorityThread();
//pt1.setPriority(Thread.MAX_PRIORITY);
pt2.setPriority(Thread.NORM_PRIORITY);
pt3.setPriority(Thread.MIN_PRIORITY);
pt1.start();
pt2.start();
pt3.start();
Thread.sleep(1000);
pt1.stop();
pt2.stop();
pt3.stop();
System.out.println("Max priority thread "+pt1.count);
System.out.println("Normal priority thread "+pt2.count);
System.out.println("Min priority thread "+pt3.count);
}
}

Thread Priorties
Output:
Max priority thread 646288206
Normal priority thread 47287546
Min priority thread 0

Thread Synchronization
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
synchronization is achieved is called
thread synchronization.
Without Synchronization
class TwoStrings {
static void print (String str1, String str2) {
System.out.print(str1);
try {
Thread.sleep(500);
} catch (InterruptedException ie) {
e.printStackTrace();
}
System.out.println(str2);
}
}

Without Synchronization
class PrintStringsThread implements Runnable {
String str1, str2;
PrintStringsThread(String str1, String str2) {
this.str1 = str1;
this.str2 = str2;
new Thread(this).start();
}
public void run() {
TwoStrings.print(str1, str2);
}
}


Without Synchronization
public class ThreadUnsyncDemo {
public static void main(String args[]) {
new PrintStringsThread (Hello , there.);
new PrintStringsThread (How are , you?);
new PrintStringsThread (Thank you ,very much!);
}
}
Result:
Hello How are Thank you very much!
you?
there.


Thread Synchronization
class TwoStrings1 {
synchronized static void print (String str1, String
str2){
System.out.print(str1);
try{
Thread.sleep(1000);
} catch (InterruptedException ie) {
e.printStackTrace();
}
System.out.println(str2);
}
}

Thread Synchronization
class PrintStringsThread1 implements Runnable {
String str1, str2;
PrintStringsThread1(String str1, String str2) {
this.str1 = str1;
this.str2 = str2;
new Thread(this).start();
}
public void run() {
TwoStrings1.print(str1, str2);
}
}
Thread Synchronization
public class ThreadSyncDemo {
public static void main(String args[]) {
new PrintStringsThread1 (Hello , there.);
new PrintStringsThread1 (How are , you?);
new PrintStringsThread1 (Thank you ,very much!);
}
}

Result
Hello there.
How are you?
Thank you very much!


Wait(), notify()
Multithreading replaces event loop programming by dividing your tasks into
discrete and logical units. Threads also provide a secondary benefit: they do away
with polling. Polling is usually implemented by a loop that is used to check some
condition repeatedly. Once the condition is true, appropriate action is taken. This
wastes CPU time. For example, consider the classic queuing problem, where one
thread is producing some data and another is consuming it. To make the problem
more interesting, suppose that the producer has to wait until the consumer is
finished before it generates more data. In a polling system, the consumer would
waste many CPU cycles while it waited for the producer to produce. Once the
producer was finished, it would start polling, wasting more CPU cycles waiting for
the consumer to finish, and so on. Clearly, this situation is undesirable.
To avoid polling, Java includes an elegant interprocess communication
mechanism via the wait( ), notify( ), and notifyAll( ) methods. These methods
are implemented as final methods in Object, so all classes have them. All three
methods can be called only from within a synchronized method.
wait( ) tells the calling thread to give up the monitor and go to sleep until some
other thread enters the same monitor and calls notify( ).
notify( ) wakes up the first thread that called wait( ) on the same object.
notifyAll( ) wakes up all the threads that called wait( ) on the same object. The
highest priority thread will run first

// An incorrect implementation of a
producer and consumer.
class Q {
int n;
synchronized int get() {
System.out.println("Got: " + n);
return n;
}
synchronized void put(int n) {
this.n = n;
System.out.println("Put: " + n);
}
}
// An incorrect implementation of a
producer and consumer.
class Producer implements Runnable {
Q q;
Producer(Q q) {
this.q = q;
new Thread(this, "Producer").start();
}
public void run() {
int i = 0;
while(true) {
q.put(i++);
}
}
}
// An incorrect implementation of a
producer and consumer.
class Consumer implements Runnable {
Q q;
Consumer(Q q) {
this.q = q;
new Thread(this, "Consumer").start();
}
public void run() {
while(true) {
q.get();
}
}
}
// An incorrect implementation of a
producer and consumer.
class PC {
public static void main(String args[]) {
Q q = new Q();
new Producer(q);
new Consumer(q);
System.out.println("Press Control-C to
stop.");
}
}
// An incorrect implementation of a
producer and consumer.
Result:
Put: 1
Got: 1
Got: 1
Got: 1
Got: 1
Got: 1
Put: 2
Put: 3
Put: 4
Put: 5
Put: 6
Put: 7
Got: 7
wait( ) and notify( )
As you can see, after the producer put 1,
the consumer started and got the same 1
five times in a row. Then, the producer
resumed and produced 2 through 7
without letting the consumer have a
chance to consume them.
The proper way to write this program in
Java is to use wait( ) and notify( ) to
signal in both directions, as shown here
Wait and Notify Threads
class Que1 {
int n;
boolean flag = false;
synchronized int get() {
if(!flag)
try{
wait();
}catch (InterruptedException e) {
System.out.println(Exception);
}
System.out.println(Get: +n);
flag = false;
notify();
return n;
}
Wait and Notify Threads
synchronized void put(int n) {
if(flag)
try{
wait();
}catch (InterruptedException e) {
System.out.println(Exception);
}
this.n = n;
System.out.println(Put: +n);
flag = true;
notify();
}
}//end Que1 class

Wait and Notify Threads
class Producer1 implements Runnable{
Que1 q;
Producer1(Que1 q){
this.q = q;
new Thread(this,").start();
}
public void run() {
int i=0;
while(i<=10){
q.put(i++);
}
}
}
Wait and Notify Threads
class Consumer1 implements Runnable{
Que1 q;
Consumer1(Que1 q){
this.q = q;
new Thread(this,").start();
}
public void run() {
while(true){
q.get();
}
}
}

Wait and Notify Threads
public class WaitNotifyDemo {
public static void main(String args[]) {
Que1 q = new Que1();
new Producer1(q);
new Consumer1(q);
}
}


Wait and Notify Threads
Result:
Put: 0
Get: 0
Put: 1
Get: 1
Put: 2
Get: 2
Put: 3
Get: 3
Put: 4
Get: 4
Put: 5
Get: 5
Put: 6
Get: 6
Put: 7
Get: 7
Put: 8
Get: 8
Put: 9
Get: 9
Put: 10
Get: 10

stop(), suspend() and resume()
stop(), suspend() and resume() are the methods used
for thread implementation. stop() - terminate the
thread execution, Once a thread is stopped, it cannot
be restarted with the start() command, since stop() will
terminate the execution of a thread. Instead you can
pause the execution of a thread with the sleep()
method. The thread will sleep for a certain period of
time and then begin executing when the time limit is
reached. But, this is not ideal if the thread needs to be
started when a certain event occurs. In this case, the
suspend() method allows a thread to temporarily
cease executing. resume() method allows the
suspended thread to start again.
DeadLock
A deadlock is a situation in which two or more competing actions are
each waiting for the other to finish, and thus neither ever does.
In an operating system, a deadlock is a situation which occurs when a
process enters a waiting state because a resource requested by it is
being held by another waiting process, which in turn is waiting for
another resource. If a process is unable to change its state indefinitely
because the resources requested by it are being used by other waiting
process, then the system is said to be in a deadlock
Below Both processes need both resources. P1 requires additional
resource R1, P2 requires additional resource R2; neither process can
continue.

DeadLock
Deadlock describes a situation where two or
more threads are blocked forever, waiting for
each other.
Deadlock is the phenomenon when, typically,
two threads each hold an exclusive lock that
the other thread needsin order to continue;
in principle, there could actually be more
threads and locks involved;
DeadLock
A special type of error that you need to avoid that
relates specifically to multitasking is deadlock, which
occurs when two threads have a circular dependency
on a pair of synchronized objects. For example,
suppose one thread enters the monitor on object X
and another thread enters the monitor on object Y. If
the thread in X tries to call any synchronized method
on Y, it will block as expected. However, if the thread in
Y, in turn, tries to call any synchronized method on X,
the thread waits forever, because to access X, it would
have to release its own lock on Y so that the first
thread could complete. Deadlock is a difficult error to
debug for two reasons:
Deadlock
class A {
synchronized void foo(B b) {
String name = Thread.currentThread().getName();
System.out.println(name + " entered A.foo");
try {
Thread.sleep(1000);
} catch(Exception e) {
System.out.println("A Interrupted");
}
System.out.println(name + " trying to call B.last()");
b.last();
}

synchronized void last() {
System.out.println("Inside A.last");
}
}


Deadlock
class B {
synchronized void bar(A a) {
String name = Thread.currentThread().getName();
System.out.println(name + " entered B.bar");
try {
Thread.sleep(1000);
} catch(Exception e) {
System.out.println("B Interrupted");
}
System.out.println(name + " trying to call A.last()");
a.last();
}

synchronized void last() {
System.out.println("Inside A.last");
}
}


Deadlock
class Deadlock implements Runnable {
A a = new A();
B b = new B();

Deadlock() {
Thread.currentThread().setName("MainThread");
Thread t = new Thread(this, "RacingThread");
t.start();
a.foo(b); // get lock on a in this thread.
System.out.println("Back in main thread");
}
public void run() {
b.bar(a); // get lock on b in other thread.
System.out.println("Back in other thread");
}

public static void main(String args[]) {
new Deadlock();
}
}

output
When you run this program, you will see the output shown here:
MainThread entered A.foo
RacingThread entered B.bar
MainThread trying to call B.last()
RacingThread trying to call A.last()

Because the program has deadlocked, you need to press CTRL-
C to end the program. You can see a full thread and monitor
cache dump by pressing CTRL-BREAK on a PC .
You will see that RacingThread owns the monitor on b, while it is
waiting for the monitor on a. At the same time, MainThread
owns a and is waiting to get b. This program will never
complete. As this example illustrates, if your multithreaded
program locks up occasionally, deadlock is one of the first
conditions that you should check for.

S-ar putea să vă placă și