Threads:-
-
A thread
represents a process or Execution
//PROGRAM-1find
out the currently running thread
class
Current
{
public
static void main(String args[])
{
System.out.println("this
is first line");
Thread
t = Thread.currentThread();
System.out.println(t);
System.out.println("Name
= " + t.getName());
}
}
In
every java program the default is main thread
The
purpose of thread is to execute the statements one by one.
Executing
the statements is of two types
1)
single tasking
2)
Multi tasking
1)
Single tasking:-
Single tasking execute only one job at
a time by the processor is called single tasking.
2)
Multi tasking:-
Executing several tasks
simultaneously is called multitasking.
Time
slicing:-
The part of the time allotted for each job
by Microprocessor.
Round
Robin Method:-
The microprocessor goes to the
first job after it has executed the last job , in a cyclic manner is called
round robin method.
Processed
based Multitasking:-
Executing several programs at a time is
called process based Multi tasking.
Thread
based Multitasking:-
Executing different parts of the same
program with the help of threads is called thread based multitasking.
Multithreading:-
Using more than one thread is called
Multithreading
Threads
are light weight process.
IIQ)
why thread is called lightweight process?
A
thread is a lightweight process it uses less resources of the system.
Uses
of threads:-
1)
Threads are used
at server side programs to handle multiple clients.
2)
Threads are used
in Animation and games.
Creating
a Thread:-
1.
write a class
that extends Thread class or implements runnable Interface.
2.
Thread a runnable
interface in java.lang package
3.
write public void
run() methods inside that class
note:- A thread can execute the statements
of run method only.
4.
create an object
to the class
5.
create a thread
and attach the thread to that object
6.
thread t = new
thread( obj , ”threadname”);
7.
Run the thread on
the object.
//creating
a thread and running it.
class
Myclass extends Thread
{
boolean
stop = false;
public
void run()
{
for(int
i=1;i<100000;i++)
{
System.out.println(i);
if(stop)
return;
}
}
}
class
TDemo
{
public
static void main(String args[]) throws Exception
{
//create
an object to myclass
Myclass
obj = new Myclass();
//create
a thread and attach thread to that object
Thread
t = new Thread(obj);
//Run
the thread
t.start();
System.in.read();
obj.stop=true;
}
}
how can you stop the thread
Stop
method is deprecated
1)
create a Boolean
variable and store false in that variable
boolean stop = false;
2)
Make this
variable true when the thread should be stopped
//stop
the thread when enter pressed
System.in.read();
Obj.sop
= true;
3)
if the variable
is true return from the run() method
if(stop)
return;
కామెంట్లు లేవు:
కామెంట్ను పోస్ట్ చేయండి