Suresh Rohan's Blog

This blog is all about Java, J2EE,Spring, Angular, React JS, NoSQL, Microservices, DevOps, BigData, Tutorials, Tips, Best practice, Interview questions, Views, News, Articles, Techniques, Code Samples, Reference Application and much more

Tuesday, November 3, 2015

Concurrent Programming in Java



Running multiple threads in parallel at the same time is called multi-threading or concurrency.

The Object and Thread classes and the Runnable interface provide the necessary support for concurrency in Java.

The Object class has methods like wait(), notify()/notifyAll(), etc., which are useful for multi-threading. all the objects have some basic multi-threading capabilities

Important Threading-Related Methods



Important Threading-Related Methods in the Object Class



Creating Threads


A Java thread can be created in two ways: by extending the Thread class or by implementing the Runnable interface. Both of them have a method named run().

The JVM will call this method when a thread starts executing. You can think of the run() method as a starting point for the execution of a thread, just like the main() method.

Extending the Thread Class


If you don’t override the run() method, the default run() method from the Thread class will be called, which does nothing.

To override the run() method, you need to declare it as public; it takes no arguments and has a void return type—in other words, it should be declared as public void run().

A thread can be created by invoking the start() method on the object of the Thread class (or its derived class). When the JVM schedules the thread, it will move the thread to a runnable state and then execute the run() method.

When the run() method completes its execution and returns, the thread will terminate.

MyThread1.java
package com.appfworks.threads;

/**
* Created by suresh on 03/11/15.
*/
class MyThread1 extends Thread {
public void run() {
try {
sleep(1000);
}
catch (InterruptedException ex) {
ex.printStackTrace();
// ignore the InterruptedException - this is perhaps the one of the
// very few of the exceptions in Java which is acceptable to ignore
}
System.out.println("In run method; thread name is: " + getName());
}
public static void main(String args[]) {
Thread myThread = new MyThread1();
myThread.start();
System.out.println("In main method; thread name is: " +
Thread.currentThread().getName());
}
}

Spawning a new thread from the main method


Implementing the Runnable Interface


The Runnable interface declares a sole method, run().



// in java.lang package
public interface Runnable {
public void run();


}

When you implement the Runnable interface, you need to define the run() method. Remember Runnable doesnot declare the start() method. So, how do you create a thread if you implement the Runnable interface? Thread has an overloaded constructor, which takes a Runnable object as an argument.

MyThread2.java
package com.appfworks.threads;

/**
* Created by suresh on 03/11/15.
*/
class MyThread2 implements Runnable {
public void run() {
System.out.println("In run method; thread name is: " +
Thread.currentThread().getName());
}
public static void main(String args[]) throws Exception {
Thread myThread = new Thread(new MyThread2());
myThread.start();
System.out.println("In main method; thread name is: " +
Thread.currentThread().getName());
}
}

To create a thread you must pass the object of the class to the Thread constructor.

Should you extend the Thread or implement the Runnable?

  1. run() method -  The Thread  class has the default implementation of the run()  method, so if you don’t provide a definition of the run()  method while extending the Thread  class, the compiler will not complain. However, the default implementation in the Thread  class does nothing , so if you want your thread to do some meaningful work, you need to still define it. The Runnable  interface declares the run()  method, so you must  define the run()  method in your class if you implement the Runnable interface.
  2. single inheritance -  if you extend from Thread , you cannot extend from any other class.
  3. Methods in Thread Class-  In the example you saw for getting the name of the thread, you had to use Thread.currentThread().getName()  when implementing the Runnable interface whereas you just used the getName()  method directly while extending Thread.

The Start( ) and Run( ) Methods


If you call the run() method directly, it simply executes as part of the calling thread. It does not execute as a thread: it doesn’t get scheduled and get called by the JVM.

Thread Name, Priority, and Group


Every thread has a name, which you can used to identify the thread. If you do not give a name explicitly, a thread will get a default name. 

The priority can vary from 1, the lowest, to 10, the highest. The priority of the normal thread is by default 5, and you can change this default priority value by explicitly providing a priority value. 

Every thread is part of a thread group.

You can programmatically access the minimum, normal, and maximum priority of the threads using the static members MIN_PRIORITY, NORM_PRIORITY, and MAX_PRIORITY.

Using the Thread.sleep() Method


You use the static method sleep() available in the Thread class for putting the current thread to sleep (or pause) for a certain time period

Using Thread’s Join Method


The Thread class has the instance method join() for waiting for a thread to “die.

Asynchronous Execution


You can neither predict nor control the order of execution of threads!





No comments:

Post a Comment