Sie sind auf Seite 1von 12

INTRODUCTION:

Actually java is designed to meet the real-world requirements of creating interactive,


networked programes for programmers.To do this,java provides the facilty of multithreaded
programming in which allows you to write programs that do several things simultaneously.

MULTITHREADING:
A program that has two or more independent subtasks is called as multithreaded program
and each of these independent subtasks is called a thread. it means that each subtask hass its own
path of execution. playing a computer game is a typical example of a multithread program.
Generally a game is combination of multiple threads. each subtask is called a thread.therefore
each thread runs by itself and has the CPU to itself. it is the internal mechanism hat actually
divides CPU time for each thread.

actually,mulithreading is a refined form of a time sharing system. in time sharing system the
CPU executes each process (a self-contained runnig program with its own address space)for a
few milliseconds,then saving its state and switching to the next program.

Difference between multithreading and multi taksing :

Multi threading is a specilized form of a multitasking. More than one thread executing
concurrently is called multi threading. More than one process executing concurrently is called
multitaksing. A thread is a light-weight process where as is multitasking is very heavy weight
process.thread can share the common address space. But the process can not share a common
address space.

The main thread() :


When a java program starts then very first time the main thread will be called. Generally it is
called main. From which the child threads will be executed.When you start the program, the
main thread automatically created, it can be controlled by a Thread class object.

CurrentThread() : this method returns the current runnding thread to the Thread class object.

Syntax:
Static Thread currentThread();

SetName() : this method can be used to set the internal name of the thread

class ThreadDemo
{
public static void main(String arg[])
{
Thread th=new Thread.currenThread();
System.out.println("The present thread is "+th);
th.setName("ThreadNew");
System.out.println("New Thread is "+th);
}
}

The present thread is : Thread[main,5,main]


New Thread is ThreadNew

In the above output the statement Thread[main,5,main], in which the first argument main is the
mainthread, 5 is thread priority and third argument main is thread group

CREATING AND RUNNING A THREAD:

there are two ways to create a new thread in java program:

* create a new class as a subclass of the THREAD class or

* declares a class implementing the runnable interface

java's complete multithreading system is built upon the THREAD class


and its companion interface

Runnable. you can't create a new hread on its own.therefore to create


a new thread we will either extends a THREAD class or implementing the
runnable interface.

The first wayt to create a thread is to create a new class by extending a Thread class. The
extending class must override the run() method. The run method must be called by start()
method.
Extending a thread class :
class MyThread extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("Child Thread "+getName()+"i"+i);
}
System.out.println("Exit from Child Thread" +getName());
}
}
class td
{
public static void main(String arg[])
{
MyThread t1=new MyThread();
MyThread t2=new MyThread();
MyThread t3=new MyThread();
t1.setName("First");
t2.setName("Second");
t3.setName("Third");
t1.start();
t2.start();
t3.start();
System.out.println("Exit from main thread ");
}
}

Implementing Runnable interface : We can create a new thread by implementing the


Runnable interface. The Runnamble interface requires only one method to be implemented the
run() method. it does the real work a thread is placed in its run() method
class MyThread implements Runnable
{
Thread t1,t2,t3;

MyThread()
{
t1=new Thread(this,"First");
t2=new Thread(this,"Second");
t3=new Thread(this,"Third");

t1.start();
t2.start();
t3.start();

public void run()


{
String st=new String();

for(int i=1;i<=5;i++)
{
st=Thread.currentThread().getName();
System.out.println("Thread name is "+st+"i "+i);
}
System.out.println("Exit from Child Thread "+st);
}

}
class tdimp
{
public static void main(String arg[])
{
MyThread m=new MyThread();
System.out.println("Exit from main Thread ");
}
}

Thread control methods :


Java provides several methods defined in java.lang.Thread class, that controls the
execution of a thread class.some of the most commonly used methods

void start() : A thread execution starts by calling start() method which, in turns the run() method.
The start method throws an IllegalThreadException.

void stop() : This method is used to stop the execution of a thread.

void suspend() : This method is used to temporirly stop the execution of a thread. When the code
encounters suspend() method, it saves all the states and resources of the Thread. It can be called
again by resume() method.

void resume() : This method resume the suspend() method.

static void sleep() : it suspends the the thread for executing for a minimum of the specified time
period. It throws an InterruptedException. So you need to define try-catch statements.

void join() : the thread who calls this method waits for itself to die. It throws an
InterruptedException.

static void yield() : this method is temporarily stops the execution of the caller’s thread and
places the caller’s thread at the end of the queue to wait for another to be executed.

isAlive() : this methods determines that the thread is still running or not. It returns a boolean
value such as true/false.
Class MyThread extends Thread
{
public void run()
{
try
{
for(int i=1;i<=5;i++)
{
System.out.println(“Child Thread name is “+getName()+”i “+_i);
Thread.sleep(10000);
}
}
catch(InterruptedException e)
{ }

System.out.println(“Exit from child thread “+getName());


}
}

class Thdemo
{
public static void main(String arg[])
{
MyThread f=new MyThread();
MyThread s=new MyThread();
MyThread t=new MyThread();

f.setName(“First”);
s.setName(“Second”);

f.start();
s.start();
System.out.println(“First thread is live “+f.isAlive());
System.out.println(“Second thread is ive “+s.isAlive());

try
{
System.out.println(“Waiting to finish first thread “);
f.join();

System.out.println(“Waiting to finish second thread “);


s.join();

}
catch(InterruptedException e)
{ }
System.out.println(“First thread is live “+f.isAlive());
System.out.println(“First thread is live “+s.isAlive());

/*

Thread Exceptions:

we have already seen about exception handling. in some of the


situations a thread will also throws an exception.

when you call a sleep()method, it throws an Interrupted Exception


whenever you call thread methods that are likely to throw
exceptions, you need to write an approprite exception handler.

in multithreading the catch clause may take one of the following


forms:

try

//thread method calls


}
catch(IllegalThreadStateException e)

}
------------
}
catch(InterruptedExcepion e)
{
-------------
catch(Exception e)

----------

Thread Protiries :
Every thread in java is assigned a prority value. it is the priority value that effects the
execution of a thread. The thread with the highest priority value is given preference, that is
higher-priority get more cpu time than lower priority threads.

Thread priority values that can be assigned to user created are simple integers ranging
between thread.MIN_PRIORITY and thread.MAX_PRIORITY. if you dont explicitly then by
default each thread is given priority thread.NORM_PRIORITY. generally thread priority
represents from 1 to 10. 1 means very low priority, it is represented with MIN_PRIORITY,10
means MAX_PRIORITY and 5 means NORM_PRIORITY.

class thpri extends Thread


{

thpri(String st)
{
super(st);
}

public static void main(String arg[])


{
thpri t1=new thpri("First");
thpri t2=new thpri("Second");

t1.setPriority(1);
t2.setPriority(10);

t1.start();
t2.start();
}
public void run()
{
String name=" ";
for(int i=1;i<=3;i++)
{
name=Thread.currentThread().getName();

System.out.println("name is "+getName()+i);

System.out.println("name is "+getName()+i);
}
}
}

Synchronisation of threads :

When two or more threads need to share a resource, you must ensure
that the resource will be used by only thread at a time.

for example two threads are performing reading/write from a


file. it may be cross the file. so if we use synchronized it first
complets one thread(job) after that it does the another thread.
so it prevents the crossing of a program.

*/

class synd
{

synchronized static void show(String st)


{
System.out.print("\n["+st);
try
{
Thread.sleep(1000);
}
catch(Exception e)
{
System.out.println("Interrupted ");
}
System.out.print("]");
}

class MyTh extends Thread


{
String ms=new String();

public MyTh(String st)


{
ms=st;
}
public void run()
{
synd.show(ms);
}
}
class multi
{
public static void main(String arg[])
{
MyTh t1=new MyTh("First");
MyTh t2=new MyTh("Second");
MyTh t3=new MyTh("Third");

t1.start();
t2.start();
t3.start();
}
}

output:
[First]
[Second]
[Third]
suppose if you write

public static void show(String st)


{
System.out.print("\n["+st);
try
{
Thread.sleep(1000);
}
catch(Exception e)
{
System.out.println("Interrupted ");
}
System.out.print("]");
}

output :

[First
[Second
[Third
]
]
]

Thread life cycle:

Born
|
|
| start() |
| |
| ------------ Ready
| ||
| ||
| yield()| |scheduled()
| ||
| Running ----------dead
|
| stop()
| or
| run()
| complete
|
| -----------------------------------
| | | | |
| wait() | sleep()| suspend()| i/o |locked()
| | | | |
| Ready Sleeping Suspend Blocked
| | | | |
| notify()| sleepti| meout resume()| i/o finished()
| | | | |
| -----------------------------------
| |
--------------------------------|

Bord Thread : a threa enters into a born state immediately after its
creation. that is it enters into a born statem after creating the
thread new statement is executed.

Thread Threadobject=new Thread(this);

Ready Thread :
the ready thread remains in the born state unit it calls the
start() method.

threadobject.start();

after the start() method is called, the thread will be


put into the runnable state.

Runnable thread :
when the start() method of a thread is called , the thread enters the
runnable state. the highest priority ready thread enters the running
state after execution of its start() method that executes the run()
method automatically.

Blocked Thread :
A thred comes into blocked state when any one of the following
occures.

A running thread enters the waiting system by calling wait() method


A running thread enters the sleeping state with the sleep() method.
A running thread enters the suspend state as itself

Dead Thread : a thread enters the dead state when its execution
finish or it is stopped by another thread calling its stop() method.
you cannot restart a dead thread.

java provides four threads for interthread communication.

wait() : the wait() method tells the current thread to give up the
monitor and go to sleep until another thread calls eithers notify()
method.

The notify() : this method wakes up the first method that called
wait() on same object.

The notifyAll() : this method wakes up all the threads that are waiting
on the same object for the monitor.

the yield() : it transfers the current thread to sleep and executes


the next thread in the queue.