Threads
A Thread represents a separate path of execution of a group of statements.in java program,if we write a group of statements then these statements are executed by JVM one by one.This execution is called Thread. because JVM uses a thread to execute these statements.So there is always a thread running internally.Let us write a simple program to see this internal thread...
/**
* @author Abhinaw.Tripathi
*/
public class SimpleThreadProgram {
/**
* @param args
*/
public static void main(String[] args)
{
System.out.println("Let us find current thread");
Thread t=Thread.currentThread();
System.out.println("Current Thread and its name is :" + t.getName());
}
}
A Thread represents a separate path of execution of a group of statements.in java program,if we write a group of statements then these statements are executed by JVM one by one.This execution is called Thread. because JVM uses a thread to execute these statements.So there is always a thread running internally.Let us write a simple program to see this internal thread...
/**
* @author Abhinaw.Tripathi
*/
public class SimpleThreadProgram {
/**
* @param args
*/
public static void main(String[] args)
{
System.out.println("Let us find current thread");
Thread t=Thread.currentThread();
System.out.println("Current Thread and its name is :" + t.getName());
}
}
Output:
Let us find current thread
Current Thread and its name is :main
So ,currentThread() is a static method in Thread class and its default priority is 5 .
So which thread always runs in a java program my default?
Ans: main thread
A thread represents execution of statements .The way the statement are executed is of two types:
- Single Tasking
- Multi-tasking
Lets no be confused with the process and threads both are different things.let see how?.
Single Tasking:
A task means doing some calculation,processing ,etc.Generally, a task involves execution of a group of statements eg. executing a program.So in single tasking environment ,only one task is given to the processor at a time.This means we are wasting a lot of processing time and microprocessor has to sit idle without any job for a long time.This is the drawback in single tasking.
Multi Tasking:
To use the processors time in an optimum way,we can give it several jobs at a time.This is called Multi-tasking.
Suppose there are 4 tasks that we want to execute.We load them into the memory.The memory is divided into 4 parts and the jobs are loaded there.Now the microprocessor has to execute them all at a time.So processor will take small time duration like a millisecond and divide this time between the number of jobs.here 4 jobs so we get 1/4 millisecond time for executing each of the processor time is called "Time-Slice".it will try to execute the job in this time frame.basically we use the processor time in an optimum way.
Multi Tasking is of two types:
- Process-Based Multi Tasking = Several programs are executed at a time by the microprocessor.
- Thread-Based Multi Tasking = Each thread can be imagined as an individual process that can execute a separate set of statements.
Why threads are called light-weight?
Ans: Threads are called light-weight because they utilize minimum resources of the system.This means they take less memory and less process time.
What is difference between Single and Multi Tasking ?
Ans: Executing only one job at time is called Single Tasking and Executing multiple task at a time is called Multi-Tasking.
Creating a Thread and Running it:
We all know that in java there is a main thread available already. Apart from this main thread,we can also create our own thread in a program by two ways,
- create a class that extends Thread class
- implements Runnable interface
Both of the them found in java.lang package .
Eg. class MyClass extends Thread
or
class MyClass implements Runnable
Now,in this class,write a run () method as
public void run()
{
// statements ;
}
By default ,this run () method is recognized and executed by a thread.
Lets take an example:
/**
* @author Abhinaw.Tripathi
*
*/
class MyThread extends Thread
{
public void run()
{
for(int i=0;i<=10;i++)
{
System.out.println(i);
}
}
}
public class SampleCreateThreadProg {
/**
* @param args
*/
public static void main(String[] args)
{
MyThread object=new MyThread();
Thread t=new Thread(object);
t.start();
}
}
Output:
1
2
3
4
5
6
7
8
9
10
Terminating the Thread:
A thread will terminate automatically when it comes out of run() method.now to terminate a thread on our own,we have to design our logic such as
- Create a boolean type variable and initialize it to false;
- boolean stop=false;
- Let us assume that we want to terminate the thread when the user presses <Enter> key.So,when the user presses that key,make the boolean type variable as true.
- stop=true;
public void run()
{
if(stop==true)
return;
}
Lets take an example:
/**
* @author Abhinaw.Tripathi
*
*/
class MyThreadStop extends Thread
{
boolean stop=false;
public void run()
{
for(int i=0;i<=10;i++)
{
System.out.println(i);
if(stop)
return;
}
}
}
public class StopThreadProg
{
public static void main(String[] args) throws IOException
{
MyThreadStop obj=new MyThreadStop();
Thread t=new Thread(obj);
t.start();
System.in.read();
obj.stop=true;
}
}
Output: 0
1
2
3
4
5
6
7
8
9
10
....
press <Enter> to stop the thread at any time.
What is the difference between extends thread and implement runnable ?Which one is advantageous?
Ans: extends thread and implements Runnable --both are functionally same. but when we write extends Threads,there is no scope to extend another class as multiple inheritance is not supported in java.
If we write implements Runnable ,the still there is scope to extends another class and this is advantageous for the programmer because he has a scope to extend another class too.
Which method is executed by the thread by default?
Ans: public void run() method .
Single Tasking Using a Thread:
/**
* @author Abhinaw.Tripathi
*
*/
class MyThreadd implements Runnable
{
@Override
public void run()
{
task1();
task2();
task3();
}
private void task3()
{
System.out.println("This is task 3");
}
private void task2()
{
System.out.println("This is task 2");
}
private void task1()
{
System.out.println("this is task 1");
}
}
public class SingleTaskingUsingThread
{
public static void main(String[] args)
{
MyThreadd obj=new MyThreadd();
Thread t=new Thread(obj);
t.start();
}
}
Output:
this is task 1
This is task 2
This is task 3
Multi Tasking Using Threads:
/**
* @author Abhinaw.Tripathi
*
*/
class Threadclass implements Runnable
{
private String str;
public Threadclass(String strr)
{
this.str=strr;
}
@Override
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println(str + ":" + i);
try
{
Thread.sleep(5000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
public class MultiTaskingThread
{
/**
* @param args
*/
public static void main(String[] args)
{
Threadclass obj1=new Threadclass("Cut the Tickets");
Threadclass obj2=new Threadclass("show the Tickets");
Thread t1=new Thread(obj1);
Thread t2=new Thread(obj2);
t1.start();
t2.start();
}
}
Output:
Cut the Tickets:0
show the Tickets:0
Cut the Tickets:1
show the Tickets:1
Cut the Tickets:2
show the Tickets:2
Cut the Tickets:3
show the Tickets:3
show the Tickets:4
Cut the Tickets:4
Cut the Tickets:5
show the Tickets:5
show the Tickets:6
Cut the Tickets:6
Cut the Tickets:7
show the Tickets:7
Cut the Tickets:8
show the Tickets:8
show the Tickets:9
Cut the Tickets:9
No comments:
Post a Comment