Monday, April 29, 2013

Java Concurrency Part 1

Hi i will try to give back some of the knowledge I've learned through the years by reading blogs, so I'm going to start with a series of articles in which I will explain to you the java concurrency API, I hope you can learn something from it, as I did.

PART I - INTRODUCTION

What is a thread?

The term concurrency means tasks executing simultaneously, java supports concurrency via threads objects. A thread is a task of execution in a program. The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.

There are 2 types of threads in java, daemon and non-daemon, when the JVM starts up, there is usually a single non-daemon thread and is the one that calls the main() method of a program, and the JVM executes until a call to System.exit() has been made or all threads that are not daemon threads have died.

Making it easier to understand daemon threads can be called System threads and non-daemon threads can be called program or user threads, and an applications runs until there are not program threads, to execute.

There are two ways to create a thread:

  1. Extending the Thread class and overriding the run().
      public class Calculator extends Thread {
        public void run() {
          .....
        }
      }
Implement the Runnable interface and then create a Thread object and set the Runnable object to it.

public class Calculator implements Runnable {
    public void run() {
      .....
    }


Whether the thread extends Thread class or implements the Runnable interface, either way a Thread Object has to be created to execute the thread. But creating an Object of the Thread class doesn't create a new execution thread, only calling the start() method creates a new execution thread.
  1. If thread object extends Thread: 
     Calculator calculator = new Calculator (); calculator.start();
  2. If thread object implements Runnable:
      Thread thread = new Thread(new Calculator ())
      thread.start();
Thread states

A thread has the following states:

New: The Thread object has been created, but start() has not been invoked, at this point is not consider alive.
Runnable: start() has been invoked and is eligible to run, but the schedule has not selected it.
Running: The thread is selected by the scheduler and executes the run().
Waiting/blocked/sleeping: Thread is alive but NOT ELIGIBLE TO RUN.
Dead: run() has completed.

After calling start() method the jvm does the following:
  1. A new thread of execution starts.
  2. The thread moves from new state to runnable state.
  3. When the thread gets chance to execute, its run() will execute.
A thread can be started just once, this means that a call to the start() method can not be done more than once. If start() is called more than once an IllegalThreadStateException will rise.

Running multiple threads

A thread can be identified by the following attributes.
  • ID: Unique identifier for each Thread.
  • Name: Name of Thread.
  • Priority: Threads can have a priority between one and 10, where one is the lowest priority and 10 is the highest one.
  • Status: Status of Thread. A Thread can be in one of these five states: new, runnable, blocked, waiting, or terminated.
When multiple threads run simultaneously each one gets the CPU according to the scheduler. There is not guarantee which thread will start or end first. The only guarantee is that each thread will run to completion.

 Example:
    public class Calculator extends Thread {
      public void run() {
        System.out.println(“Thread running:” + this.getName());
      }
    }
          ......
          Calculator first = new Calculator(“First”);
          first.start();
          Calculator second = new Calculator(“Second ”);
          second.start();
          ......

There is no guarantee that the order of the messages will be:
          Thread running: first
          Thread running: second
The only guarantee is that both messages will appear in console.

The join() method of the thread class suspends the execution of the calling thread until the join thread has finished.
          ...........
          Calculator first = new Calculator(“First”);
          first.start();
          try {
              first.join():
          } catch (InterruptedException e) {
              e.printStackTrace();
          }
         Calculator second = new Calculator(“Second ”);
         second.start();
         ...........

This way the console must print the message in the following order:
         Thread running: first
         Thread running: second


Go to part 2





5 comments:

  1. Hi,

    Maybe I'm wrong, I have not a well founded Thread knowledge. But as you say in the last paragraf "The join() method of the thread class suspends the execution of the calling thread until until some other thread has finished", what means the calling thread is first no? Therefore it must wait until secof finish?

    ReplyDelete
    Replies
    1. Hi Marc,
      First I'm sorry because I repeated the until word two times. Looking at it again I noticed I didn't explained clearly enough, this is maybe because this is my first post ever but I already change it and let me explain it to you in this way:

      When you call the join() on a thread you are saying I'm going to wait for the thread to finish, so for example:

      public static void main(String[] args) {
      Thread t = new Thread();
      ....
      t.join();
      System.out.println("After join");
      .....
      }

      In this code since the main method is run by a Daemon thread, so this thread when it reaches the t.join() sentence waits for the "t" thread to finish, it "joins" to the thread, after the "t" thread finishes the Daemon thread takes back the control and executes the System.out sentence.

      I hope this makes it clear to you.

      Delete
  2. Nice Information you have written here. Really Great Stuff. I keep it bookmark for our future purpose.

    We are also Web development Company in India who provide the services in Android App Development in Nagpur , SEO Company in Nagpur , Ecommerce Website Development in Nagpur. Visit Us today

    AceZed IT Solution

    ReplyDelete