Java Thread – Executor framework, Timer and TimerTask

Author posted by Jitendra on Posted on under category Categories JAVA and tagged as Tags , with 4 Comments on Java Thread – Executor framework, Timer and TimerTask

Tutorial and example of Executor framework, Timer and TimerTask over Thread

With the Thread class you could create your own timer class using the Thread.sleep(T) method to delay action for some time . This approach, however, has some drawbacks. For periodic events, if the processing times in between the sleep periods vary significantly, then the overall timing will mismatch. Also, if you need many timer events, the program will require many threads and use up system resources.

We can create a Timer functionality withExecutor frameworks and also there is Timer and Timertask available in java.util package. We will see both methods to create Timer functionality. Continue reading “Java Thread – Executor framework, Timer and TimerTask”

Java Threading – Executor Framework and Callable Interface

Author posted by Jitendra on Posted on under category Categories JAVA and tagged as Tags with 3 Comments on Java Threading – Executor Framework and Callable Interface

Java Threading – Executor Framework and Callable Interface with example

Executer is a concept evolved from the world of Runnable interface. We have seen that how to create a thread using Runnable interface, extending thread and anonymous classes.

To run the task by implementing Runnable interface, we must have to create the object of the Thread like new thread(RunnableObject).start().  But we know that creating thread have its own overheads and stored in Stack and Heap memory. It’s very expensive to create a thread object just only to run the task in separate thread.

Executors framework (java.util.concurrent.Executor), released by the JAVA 5 in package java.util.concurrent is used to run the Runnable thread objects without creating the Thread object.

The Executor framework is a framework for standardizing invocation, scheduling, execution, and control of asynchronous tasks according to a set of execution policies.

There are three types of implementations provided by the Java:

  1. ExecutorService
  2. ThreadPoolExecutor
  3. Executors (A Class containing factory methods)

To read documentation of Executor framework, refer this URL:
http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/Executor.html

Continue reading “Java Threading – Executor Framework and Callable Interface”

Daemon Thread

Author posted by Jitendra on Posted on under category Categories JAVA and tagged as Tags with 1 Comment on Daemon Thread

Example and Explanation of Daemon thread in JAVA

In java we have two types of Threads: Daemon Thread and User Threads. Generally all threads created by programmer are user thread (unless you specify it to be daemon or your parent thread is a daemon thread).

User thread is generally meant to run our program code. JVM doesn’t terminate unless all the user thread terminate.
On the other hand we have Daemon threads. Typically these threads are service provider threads. They should not be used to run your program code but some system code. These threads run parallel to your code but survive on the mercy of the JVM. When JVM finds no user threads it stops and all daemon thread terminate instantly. Thus one should never rely on daemon code to perform any program code. Continue reading “Daemon Thread”

Create Thread using Anonymous class and Interface

Author posted by Jitendra on Posted on under category Categories JAVA and tagged as Tags , with 4 Comments on Create Thread using Anonymous class and Interface

Demonstration of creating Thread by Anonymous class and Interface

Create thread using Anonymous class:

Anonymous Class

Explanation:-  A Class which does not have any name is known as anonymous class.

Q. Write a program to create thread using anonymous class/local class.

class testAno
{
  public static void main(String args[])
  {
     Thread t =new Thread(new runnable(){
     public void run()
     {
          System.out.println("I am in Thread");
     }
    });

    t.start();
}
}

O/P:-    I am in Thread

Create Thread Using Interface   OR Runnable Interface:

class Method
{
  public static void main(String args[])
  {
     TestThread runnable_obj=new TestThread();
     Thread t=new Thread(runnable_obj);
     t.start();
  }
}

class TestThread implements Runnable
{
  public  void run()
  {
     System.out.println("In Thread Main");
  }
}

Thread Synchronization

Author posted by Jitendra on Posted on under category Categories JAVA and tagged as Tags with Leave a comment on Thread Synchronization

Describes Synchronization, Producer and Consumer Problem, wait(), notify(), InterThread Communication

Synchronization, Producer and Consumer Problem, wait(), notify() methods of the Thread

class Controller
{
  private int counter;

  public void set(int i)
  {
      counter=i;
  }

  public int get()
  {
    return counter;
  }
}

class Producer extends Thread
{
  private Controller obj;

 public Producer(Controller c)
 {
  Obj=c;
 }

public void run()
{
 for(int i=0;I<5;i++ )
 {
   obj.set(i);
   System.out.println("put:"+j);
 }
}
}

class Consumer extends Thread
{
  private  Controller obj;

  public Consumer(Controller c)
  {
    obj=c;
  }

  public void run()
  {
    for(int  i=0;i<5;i++)
    {
        System.out.println("get:"+obj.get());
     }
  }
}

class TestSynchronization
{
 public  static void main(String args[])
 {
   Controller ctrl=new Controller;
   Producer thread1=new producer(ctrl);
   Consumer thread2=new Consumer(ctrl);
   thread1.start();
   thread2.start();
  }
}

O/P:-

put:0
get:0
get:0
get:0
get:0
get:0
put:1
put:2
put:3
put:4

Explanation:

In above program the producer creates value faster or slower than consumer that means there is no synchronization & this problem is known as producer_consumer problem.

Solution Of Producer & Customer Problem:-

Synchronized:

The synchronized block or synchronized method, allow only one thread at a time to execute.

Wait():

This method will cause the current thread to go into wait state until & unless notify() or notifyAll() is not called.

notifyAll():

It will give signal to all the threads which are in state to continue.

class Controller
{
  private int counter;
  private Boolean available=false;
  public synchronized int get()
  {
      while(available==false)
     {
      try
        {
          wait();
        }
        catch(Exception e)
        {
        }
     }
     notifyAll();
    available=false;
    return counter;
  }

 public synchronized int set(int value)
 {
   while(available==true)
   {
     try
     {
        wait();
     }
     catch(Exception e)
     {
     }
     counter=value;
     available=false;
     notifyAll();
    }
  }
}

class Producer extends Thread
{
  private Controller obj;
  public Producer(Controller c)
  {
   Obj=c;
  }

  public void run()
  {
   for(int i=0;I<5;i++ )
   {
     obj.set(i);
     System.out.println("put:"+j);
   }
 }
}

class Consumer extends Thread
{
 private  Controller obj;
 public Consumer(Controller c)
 {
  obj=c;
 }
 public void run()
 {
  for(int  i=0;i<5;i++)
  {
     System.out.println("get:"+obj.get());
  }
 }
}

class TestSynchronization
 {
  public  static void main(String args[])
  {
     Controller ctrl=new Controller;
     Producer thread1=new producer(ctrl);
     Consumer thread2=new Consumer(ctrl);
     thread1.start();
     thread2.start();
   }
}

O/P:
put:0
get:0
put:1
get:1
put:2
get:2
put:3
get:3
put:4
get:4

Background and foreground thread in c#

Author posted by Jitendra on Posted on under category Categories c# and tagged as Tags with 1 Comment on Background and foreground thread in c#

Example of Threading in C#. Includes Foreground and Background Threading.

  • Foreground threads have the ability to prevent the current application from terminating. The CLR will not shut down an application (which is to say, unload the hosting AppDomain) until all foreground threads have ended.
  • Background threads (sometimes called daemon threads) are viewed by the CLR as expendable paths of execution that can be ignored at any point in time (even if they are currently laboring over some unit of work). Thus, if all foreground threads have terminated, any and all background threads are automatically killed when the application domain unloads.
  • It is important to note that foreground and background threads are not synonymous with primary and worker threads. By default, every thread you create via the Thread.Start() method is automatically a foreground thread. Again, this means that the AppDomain will not unload until all threads of execution have completed their units of work. In most cases, this is exactly the behavior you require.

    Example:

    Thread Foreground Background
    Threading in CSharp
    
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Threading;
    namespace TestThread
    {
    class Program
    {
    static void Main(string[] args)
    {
    Program obj = new Program();
    obj.printInfo();
    //Create object of parameterized thread, so that you can pass parameter to any thread
    ParameterizedThreadStart pst = new ParameterizedThreadStart(obj.function1);
    //Bydefault threads are Foreground Thread
    Thread t1 = new Thread(pst);
    //Set Thread Name
    t1.Name = "Thread1";
    //Passs Parameter to thread
    t1.Start(true);
    //Create object of ThreadStart, it does not have any parameter
    ThreadStart ts = new ThreadStart(obj.function2);
    Thread t2 = new Thread(ts);
    t2.Name = "Thread2";
    //Make it Background Thread
    t2.IsBackground = true;
    //Run the thread
    t2.Start();
    Console.ReadKey();
    }
    public void function1(object val)
    {
    for (int i = 0; i < 5; i++)
    {
    Console.WriteLine("This is parameterized function1 by {0} and Value passed is {1} ", Thread.CurrentThread.Name, val);
    }
    }
    public void function2()
    {
    for (int i = 0; i < 5; i++)
    {
    Console.WriteLine("This is function2 by : " + Thread.CurrentThread.Name);
    }
    }
    public void printInfo()
    {
    System.Text.StringBuilder sb = new StringBuilder();
    sb.Append("*******************************************************n");
    sb.Append("            read Demo by ShivaSoft                     n");
    sb.Append("*******************************************************n");
    System.Console.WriteLine(sb);
    }
    }
    }