Thread Assignment: Q1.Explain Thread Life Cycle?
Thread Assignment: Q1.Explain Thread Life Cycle?
Thread Assignment: Q1.Explain Thread Life Cycle?
A thread can be in one of the five states. According to sun, there is only 4 states in thread
life cycle in java new, runnable, non-runnable and terminated. There is no running state.
But for better understanding the threads, we are explaining it in the 5 states.
The life cycle of the thread in java is controlled by JVM. The java thread states are as
follows:
1) New
The thread is in new state if you create an instance of Thread class but before
the invocation of start() method.
2) Runnable
The thread is in runnable state after invocation of start() method, but the
thread scheduler has not selected it to be the running thread.
3) Running
The thread is in running state if the thread scheduler has selected it.
4) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to
run.
5) Terminated
A thread is in terminated or dead state when its run() method exits.
Q2.List Thread class methods ?
Java's multithreading system is built upon the Thread class, its methods,
and its companion interface, Runnable. To create a new thread, your
program will either
extend Thread or implement the Runnableinterface.
The Thread class defines several methods that help manage threads:
Method Meaning
Now let's see how to use a Thread that begins with the main java
thread that all Java programs have.
Q3.Create Arithmetic class which extends Thread to perform all
operations.
import java.io.*;
import java.net.*;
import java.util.*;
public class Arithmetic extends Thread
{
int first,second;
Arithmetic(int a,int b)
{
first=a;
second=b;
}
public void run()
{
try
{
System.out.println("Addition of
"+first+"+"+second+" is: "+(first+second));
Thread.sleep(1000);
System.out.println("Subtraction of
"+first+"-"+second+" is: "+(first-second));
Thread.sleep(1000);
System.out.println("Multiplication of
"+first+"*"+second+" is: "+(first*second));
Thread.sleep(1000);
System.out.println("Division of
"+first+"/"+second+" is: "+(first/second));
Thread.sleep(1000);
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static void main(String a[])throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter the first no:");
int no1=Integer.parseInt(br.readLine());
System.out.println("Enter the second no:");
int no2=Integer.parseInt(br.readLine());
}
}
OUTPUT:-
Enter the first no:
10
Enter the second no:
2
Addition of 10+2 is: 12
Subtraction of 10-2 is: 8
Multiplication of 10*2 is: 20
Division of 10/2 is: 5