The main purpose of multithreading is to provide simultaneous execution of two or more parts of a program to maximum utilize the CPU time. A multithreaded program contains two or more parts that can run concurrently. Each part of such a program called a thread. Each thread has a separate path of its execution. So this way a single program can perform two or more tasks simultaneously.

  1. Multi threading
  2. Multi tasking
  3. Processor based multitasking
  4. Thread based multitasking

we use multithreading in java multi processing because threads share a common memory area. They don’t separate memory area so saves the memory and contest switching between the threads takes less time then process.

Java multi threading is mostly used games, animations etc..


The Thread class and Runnable Interface

A thread can be created in two ways:

  1. By extending Thread class
  2. By implementing Runnable interface.

Before we learn how to create the thread. Lets have a look at the methods that helps in managing the threads.

  • getName(): It is used for Obtaining a thread’s name
  • getPriority(): Obtain a thread’s priority
  • isAlive(): Determine if a thread is still running
  • join(): Wait for a thread to terminate
  • run(): Entry point for the thread
  • sleep(): suspend a thread for a period of time
  • start(): start a thread by calling its run() method

Thread creation by implementing Runnable Interface

One way of creating a thread is to create a class that implements the Runnable interface. We must need to give the definition of run() method.

This run method is the entry point for the thread and thread will be alive till run method finishes its execution.

class Multithreading
{  
  public void run(){  
    System.out.println(" thread is in running state.");  
  }   
  public static void main(String args[]){  
     Multithreading obj=new Multithreading();  
     Thread obj =new Thread(obj);  
     obj.start();  
 }  
}

Thread creation by extending Thread class

This is the second way of creating a thread. Here we need to create a new class that extends the Thread class.

The class should override the run() method which is the entry point for the new thread as described above.

class Multithreading extends Thread
{  
  public void run()
  {  
    System.out.println("My thread is in running state.");  
  }   
  public static void main(String args[])
  {  
     Multithreading obj=new Multithreading();   
     obj.start();  
  }  
}

Thread priorities

  • Thread priorities are the integers which decide how one thread should be treated with respect to the others.
  • Thread priority decides when to switch from one running thread to another, process is called context switching
  • A thread can voluntarily release control and the highest priority thread that is ready to run is given the CPU.
  • A thread can be preempted by a higher priority thread no matter what the lower priority thread is doing. Whenever a higher priority thread wants to run it does.
  • To set the priority of the thread setPriority() method is used which is a method of the class Thread Class.

Multi tasking :-

It is a processing of executing multiple tasks simenteniously . We use multi tasking utilize the multi tasking can be achieved by two ways.

  1. Process based multi tasking(multi processing)
  2. Thread based multi tasking(multi threading)

1.Process based multi tasking:-

Each process having own address in memory i.e each memory area. Process is heavy weight. cost of communication between process is high. Switching from one process to another require some time for saving and loading register, memory maps updating list etc..


2.Thread based multi tasking:-

Threads share the same address same thread is light .cost of communication between thread is low.


What is thrad in java:-

A thread is light weight sub-process a smallest unit of processing. It is a separate path of execution . threads are independent if these occurs exception in one thread it doesn’t effect other threads it shares a common memory area.


Life cycle of thread(Thread states):

A thread can be in one of the 5statements according to run there is only states in thread life in java new, runnable, non-runnable and terminated.

There is no running state.but for understanding the threads if explain at in the 5states.

The life cycle of the thread by JVM.the java Threads which follows.

  1. New
  2. Runble
  3. Running
  4. Non-runble(blocked)
  5. Dead State.

1. New:-

The thread is a new state if we create an instance of thread class before the invocation of start method.


2.Runnable:-

The thread is in runnable state invocation of start method. But the thread schedule as not selected it to the not running thread.


3.Running:-

The thread is running if the thread scheduler as selected it.


4.Non-runnable:-

There is the state when the is still alive but currently not eligible to run.


5.Dead State:-

A thread is in terminated or dead state when it’s run method exists

Example:

Class  multi extends  thread 
{
Public  void run()
{
System.out.println(“thread is running”);
}
Public  static void main(String args[])
{
Multi t1 = new multi ();
T1.state ();
}
}

Thread Methods:

S.NO Methode Discription
1public void start()Starts the thread in a separate path of execution, then invokes the run() method on this Thread object.
2public void run()If this Thread object was instantiated using a separate Runnable target, the run() method is invoked on that Runnable object.
3public final void setName(String name)Changes the name of the Thread object. There is also a getName() method for retrieving the name.
4 public final void setPriority(int priority) Sets the priority of this Thread object. The possible values are between 1 and 10.
5public final void setDaemon(boolean on)A parameter of true denotes this Thread as a daemon thread.
6public final void join(long millisec)The current thread invokes this method on a second thread, causing the current thread to block until the second thread terminates or the specified number of milliseconds passes.
7public void interrupt()Interrupts this thread, causing it to continue execution if it was blocked for any reason.
8public final boolean isAlive() Returns true if the thread is alive, which is any time after the thread has been started but before it runs to completion. The previous methods are invoked on a particular Thread object. The following methods in the Thread class are static. Invoking one of the static methods performs the operation on the currently running thread.
9public static void yield() Causes the currently running thread to yield to any other threads of the same priority that are waiting to be scheduled.
10 public static void sleep(long millisec)Causes the currently running thread to block for at least the specified number of milliseconds.
11public static boolean holdsLock(Object x)Returns true if the current thread holds the lock on the given Object.
12public static Thread currentThread()Returns a reference to the currently running thread, which is the thread that invokes this method.
13public static void dumpStack()Prints the stack trace for the currently running thread, which is useful when debugging a multithreaded application.

Major thread operations:

Core Java provides a complete control over multithreaded program. You can develop a multithreaded program which can be suspended, resumed or stopped completely based on your requirements.

There are various static methods which you can use on thread objects to control their behavior. Following table lists down those methods:

S.NO Methode Discription
1public void suspend()This method puts a thread in suspended state and can be resumed using resume() method.
2public void stop()This method stops a thread completely.
3public void resume()This method resumes a thread which was suspended using suspend() method.
4public void wait()Causes the current thread to wait until another thread invokes the notify().
5public void notify()Wakes up a single thread that is waiting on this object's monitor. Be aware that latest versions of Java has deprecated the usage of suspend( ), resume( ), and stop( ) methods and so you need to use available alternatives.

Starting a thread:

start() method of Thread class is used to start a newly created thread. It performs following tasks:

  1. A new thread starts(with new callstack).
  2. The thread moves from New state to the Runnable state.
  3. When the thread gets a chance to execute, its target run() method will run.

By extending Thread class:

class Multi extends Thread{  
public void run(){  
System.out.println("thread is running...");  
}  
public static void main(String args[]){  
Multi t1=new Multi();  
t1.start();  
 }  
} 

Who makes your class object as thread object?

Thread class constructor allocates a new thread object.When you create object of Multi class, your class constructor is invoked(provided by Compiler) fromwhere Thread class constructor is invoked(by super() as first statement). So your Multi class object is thread object now.


By implementing the Runnable interface:

class Multi3 implements Runnable{  
public void run(){  
System.out.println("thread is running...");  
}  	  
public static void main(String args[]){  
Multi3 m1=new Multi3();  
Thread t1 =new Thread(m1);  
t1.start();  
}  
}  

News Walls


Copyrights © 2016. All Rights Reserved to Learn Computers Home, India. //Site Designed.