Java multithreading

What is Multithreading? Explain the life cycle of a thread.

1. Multithreading is executing two parts of the same program concurrently.

2. Multithreading is a form of multitasking.

3. In thread based multi tasking environment, a smallest unit of sequential flow of code is a thread.

4. A program can contain more than one thread. Ex: A browser can serve a web page while downloading a file. Each of these actions is a thread.

5. The two factors to get the benefit of multithreading are:
a. The CPU idle time can be minimized
b. I/O devices such as ports, disks are much slower than the CPU. A program spends a majority of execution time waiting to send or receive data to or from a device.

6. This idle time can be used to perform another task in an application.

Life cycle of a thread

1. New State : Soon after creation of a thread, the thread is said to in the new state.

2. Runnable State: The life of a thread starts after invoking the start() method. The start() method invokes the run() method.

3. Running State: When the thread is currently running, it is in the state of running.

4. Wait State : When other threads are holding the resources, the current thread is said to be in wait state

5. Dead State: When the thread is completed the execution of run() method, it is said to be dead state. In other words, when a thread cannot ever run.

Explain how to use thread class for Multithreading in Java. Explain with an example.

Threads are used in java by

a. Extending the Thread class
b. Implementing the Runnable interface

The following is the example to extend the Thread class
public class MyThread extends Thread
{
   String message;
   MyThread(String msg)
   {
       message=msg;
   }

   public void run()
   {
       for(int count=0;count<=5;count++)
       {
           System.out.println("Run method: " + message);
       }
   }
}
The line ‘public class MyThread extends Thread’ indicates he class header.
Every thread functionality need to be implemented in the run() method.
The thread is to display the ‘counter’ value for 5 times.

The following code creates the MyThread object and invokes the run() method in it.
public class MainMyThread
{
   public static void main(String[] args)
   {
       MyThread dt1=new MyThread("Run");
       MyThread dt2=new MyThread("Thread");
       dt1.start(); // this will start thread of object 1
       dt2.start(); // this will start thread of object 2
   }
}
The start() method of both the threads invokes the run() method of MyThread class.
Similar to the above, the run() method can be implemented by implementing Runnable interface.

The following example illustrates the implementation of Runnable interface.
public class MyThread implements Runnable
{
   String message;
   MyThread(String msg)
   {
       message=msg;
   }

   public void run()
   {
       for(int count=0;count<=5;count++)
       {
           System.out.println("Run method: " + message);
       }
   }
}

The following code creates the MyThread object and invokes the run() method in it.
public class MainMyThread
{
   public static void main(String[] args)
   {
       MyThread dt1=new MyThread("Run");
       MyThread dt2=new MyThread("Thread");

       dt1.start(); // this will start thread of object 1
       dt2.start(); // this will start thread of object 2
   }
}

In order to get the advantages of both interface and a class, the Runnable interface and the Thread class can be used together in a class.

Example
public class MyClass implements Runnable extends Thread
{
   ..
   ..
}

What is Runnable interface? Explain how to use Runnable interface for Multithreading.

1. Runnable interface is available in java.lang package

2. The purpose of Runnable interface is to provide a protocol that is common for objects to execute the functionality while they are active.

3. Active means a thread has been started, but in running state.

4. The Runnable interface is implemented by the class Thread. So that the implementing class need not extend the Thread class.

5. Runnable interface supports to inherit the threading functionality other than the Thread class.

The following is the signature of Runnable interface
public interface Runnable
{
   void run();
}
To use Runnable interface, the class header should be followed by ‘implements Runnable’ phrase.

Example
public class MyClass implements Runnable
{
   .
}
The following is a complete coding example to implement Runnable interface.
class RunnableThread implements Runnable
{
   Thread runner;
   public RunnableThread()
   {
   }
   public RunnableThread(String threadName)
   {
       runner = new Thread(this, threadName); // (1) Create a new thread.
       System.out.println(runner.getName());
       runner.start(); // (2) Start the thread.
   }
   public void run()
   {
       //Display info about this particular thread
       System.out.println(Thread.currentThread());
   }
}

public class RunnableExample
{
   public static void main(String[] args)
   {
       Thread thread1 = new Thread(new RunnableThread(), "thread1");
       Thread thread2 = new Thread(new RunnableThread(), "thread2");
       RunnableThread thread3 = new RunnableThread("thread3");
       //Start the threads
       thread1.start();
       thread2.start();
       try
       {
           //delay for one second
           Thread.currentThread().sleep(1000);
       }
       catch (InterruptedException e)
       {
       }
       //Display info about the main thread
       System.out.println(Thread.currentThread());
   }
}

What are the methods of thread class in java? Explain them

The methods in thread class are :

1. start() – This method invokes the run() method, which causes the thread to begin its execution.

2. run() – This method contains the actual functionality of a thread and usually invoked by start() method.

3. sleep() – This method causes currently running thread to pause for certain milliseconds.

4. yield() - This method pauses the current thread to halt temporarily and allows other threads to execute.

5. currentThread() – This method returns the currently executing thread’s object reference

6. destroy() – This method causes the method to destroy without any cleanup process. If at all any monitors has locked, they remain locked. It is suggestible not to implement this method, which causes runtime issues of applications.

7. is Alive() – This method is used to know whether a thread is live or not. A thread is said to be alive if it has been started but not yet died.

8. setPriority() – This method changes the priority of the current thread. The min. priority number is 1 and the max. priority number is 10.

9. getPriority() – Returns the priority number of a given thread.

10. setName() – This method is used to name a thread for future identification

11. getName() - Returns the name of a given thread.

Can your explain thread priorities?

1. Every thread has a purpose.

2. As per the application’s demand, certain threads need to get the execution first.

3. At times one thread may be required to execute more times than another thread.

4. Thread priority is to select the thread that is to execute first or as per the preference.

5. More CPU cycles are allotted to the threads with highest priority.

6. The static final members Thread.MIN_PRIORITY and Thread.MAX_PRIORITY were assigned with values 1 and 10 respectively.

7. The method, setPriority() is to assign the priority to a thread and getPriority() is to get the priority number of a thread.

The following code illustrates the use of priorities of threads.
public class PriorityTest
{
   public static void main(String[] args)
   {
       Thread frank = new Thread("Frank");
       Thread mary = new Thread("Mary");
       Thread chris = new Thread("Chris");

       frank.setPriority(Thread.MIN_PRIORITY);
       mary.setPriority(Thread.NORM_PRIORITY);
       chris.setPriority(Thread.MAX_PRIORITY);

       frank.start();
       mary.start();
       chris.start();
   }
}

Explain Synchronization in Thread.

1. Every thread has its local thread registers and stack.

2. When two or more threads access the same resource, the value may not be correct.

3. In order to get the correct value, we need to get the lock to access the resource.

4. Synchronization allows the threads to access the resources in “round robin fashion”.

5. Thread synchronization is implemented in two ways – using synchronization block and synchronization methods.

6. A lock is gained on an object by a thread, before it is accessed.

7. A thread will wait in line for another thread to release the lock on same resource.

The following code illustrates the use of threads using synchronized block
public class SyncBlock
{
   private Object longLock;
   public SyncBlock()
   {
       longLock = new Object();
   }

   public void doSomething()
   {
       System.out.println("Trying to access the lock”);
       synchronized (longLock)
       {
           System.out.println("Found exclusive lock to access");
           try
           {
               Thread.sleep(10000);
           }
           catch (InterruptedException x)
           {
           }
           System.out.println("Relinquishing exclusive access to " + "longLock");
       }
   }

   private static void print(String msg)
   {
       String name = Thread.currentThread().getName();
       System.err.println(name + ": " + msg);
   }

   private static Thread launch(final SyncBlock sb, String name)
   {
       Runnable runnable = new Runnable()
       {
           public void run()
           {
               print("in run()");
               sb.doStuff();
           }
       }

       Thread thrd = new Thread(runnable, name);
       thrd.start();
       return thrd;
   }

   public static void main(String[] args)
   {
       try
       {
           SyncBlock syncBlk = new SyncBlock();

           Thread t1 = launch(syncBlk, "T1");
           Thread.sleep(500);

           Thread t2 = launch(syncBlk, "T2");
           Thread t3 = launch(syncBlk, "T3");

           Thread.sleep(1000);

           System.out.println("About to interrupt T2");
           t2.interrupt();
           System.out.println("Interrupted T2");
       }
       catch (InterruptedException intrExcp)
       {
           intrExcp.printStackTrace();
       }
}
The following code snippet illustrates using synchronized methods
public class SynchronizedThreads
{
   private int kounter = 0;
   public synchronized void increment()
   {
       kounter++;
   }

   public synchronized void decrement()
   {
       kounter--;
   }

   public synchronized int value()
   {
       return kounter;
   }
}

Explain the need for thread group.

1. Thread group is a group of threads to manage threads in a convenient manner

2. When more number of threads needs to be suspended and resumed, threads group is a nice choice

For example
one thread group is engaged for printing and another for displaying on the screen.
3. When printing is aborted, it is easy to release all threads related to printing.

The following code illustrates the use of thread group
class SampleEnumerate
{
   public void showCurrentThreads()
   {
       ThreadGroup presentGroup = Thread.currentThread().getThreadGroup();
       int numOfThreads = presentGroup.activeCount();
       Thread[] listOfThreads = new Thread[numOfThreads];

       presentGroup.enumerate(listOfThreads);
       for (int index = 0; index < numOfThreads; index++)
       System.out.println("Thread #" + index + " = " + listOfThreads[index].getName());
   }
}

   public class MainSampleEnumerate
   {
       public static void main(String[] args)
       {
           new SampleEnumerate().showCurrentThreads();
   }
}

Java file handling
Java file handling - Use of Streams, Difference between Stream classes and Reader writer classes, Explain and demonstrate the use of File, RandomAccessFile classes, Explain the use of Reader and Writer classes...
Java utility classes
Java utility classes - What is object Serialization? Explain the use of Persisting object, step of using object Deserialization...
Java socket programming
Java socket programming - What is socket? Explain the features of socket, characteristics of Java socket class, InetAddress class, DatagramSocket class, DatagramPacket class...
Post your comment