Showing posts with label Thread. Show all posts
Showing posts with label Thread. Show all posts

Thursday, June 16, 2016

Famous Thread Application(Client-Server Program) in java

Application of Threads:

In a network, a server has to render its service to several clients at a time.So by using threads at server side programs,we can make the threads serve several clients at a time.

Program:

Server Side Program:

import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 *
 */

/**
 * @author Abhinaw.Tripathi
 *
 */

class MultiServe implements Runnable
{
static ServerSocket ss;
static Socket s;

@Override
public void run()
{
String name=Thread.currentThread().getName();
for(;;)
{
try
{
System.out.println("Thread Name:"+name + "ready to accept....");
s=ss.accept();
System.out.println("Thread Name:"+name + " accept a connection....");
PrintStream ps=new PrintStream(s.getOutputStream());
ps.println("Thread "+name + " contacted you");
ps.close();
s.close();
}
catch (IOException e)
{
e.printStackTrace();
}

}
}
}

public class MultiServerApp
{
public static void main(String[] args) throws Exception
{
MultiServe ms=new MultiServe();
ServerSocket ss = new ServerSocket(999);

Thread t1=new Thread(ms, "One");
Thread t2=new Thread(ms, "Two");

t1.start();
t2.start();

}

}


Client Side Program:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

/**
 * 
 */

/**
 * @author Abhinaw.Tripathi
 *
 */
public class MultiClient 
{
public static void main(String[] args) throws IOException
{
       Socket s=new Socket("localhost", 999);   
       BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));   
       boolean str;
       
       while(str=br.readLine() !=null)
      System.out.println(str);
       
       br.close();
       s.close();
}

}

Daemon Thread and Thread Life Cycle example java

Daemon Threads

Sometimes, a thread has to continuously execute without any interruption to provide service to other threads.Such threads are called Daemon Threads.for example---oracle.exe is a program that runs continuously in a computer.

A daemon thread is a thread that executes continuously.Daemon threads are service providers for other threads or objects.It generally provides a background processing.

To make  a thread t as daemon thread,we can use setDaemon() method as:
 t.setDaemon(true);

To know if a thread is daemon or not,isDaemon() useful.
boolean x=t.isDaemon();

If  isDaemon() returns true then the thread t is a Daemon Thread,otherwise not.

Thread Life Cycle:

Starts from birth of a thread till its death, a thread exists in different states which are collectively called Thread Life Cycle.

A thread will be born when it is created using Thread Class as:

Thread t=new Thread();

Then thread goes into runnable state when start() method is called. Yeild() method may pause a thread bu the thread will be still in running state only.
A thread can go to runnable state to non-runnable state,when sleep() or wait() method acts on it.
Finally, a thread is terminated from memory only when it comes out of run() method.This happens when the thread complete its execution of run() method  and naturally comes out of it or when user force it to come out of it.

(start()---------->runnable(yeild()------->sleep()or wait()------Dead)
New Thread-->Runnable-->Non Runnable--->Dead



Thread Priorities and Thread Group example java

Thread Priorities 

When the threads are created and started, a thread scheduler program in JVM will load them into memory and execute them.This scheduler will allot more JVM time to those threads which are having higher priorities. Thread priorities vary from 1 to 10 .

What is default priority of a thread?
Ans: Default Priority=5

Program:

/**
 * @author Abhinaw.Tripathi
 *
 */

class ThreadPriorityClss extends Thread
{
int count=0;
public void run()
{
for(int i=1;i<=10000;i++)
count ++;
System.out.println("Completed Thread:" + Thread.currentThread().getName());
System.out.println("Its priority:"+Thread.currentThread().getPriority());
}
}
public class ThreadPriorityApp
{
public static void main(String[] args)
{
ThreadPriorityClss obj=new ThreadPriorityClss();
Thread t1=new Thread(obj,"One");
Thread t2=new  Thread(obj, "Two");

t1.setPriority(2);
t2.setPriority(Thread.NORM_PRIORITY);

t1.start();
t2.start();
}


}

Output:

Completed ThreadTwo
Its priority:5
Completed ThreadOne
Its priority:2

Thread Group

A thread group represents several thread as a single group.The main advantage of taking several threads as a group is that by using a single  method,we will be able to control all the threads in the group.

To create a thread group,we should simply create an object to ThreadGroup class as:

ThreadGroup tg=new ThreadGroup("groupName");

Normally,the maximum priority of a thread group will be 10 .

Program:

/**
 * @author Abhinaw.Tripathi
 *
 */
class Reservation extends Thread
{
public void run()
{
System.out.println("I am reservation thread.");
}
}

class Cancellation extends Thread
{
  public void run()
  {
 System.out.println("I am cancellation thread.");
  }
}

public class ThreadGroupApp
{
public static void main(String[] args)
{
Reservation res=new Reservation();
Cancellation cancel=new Cancellation();
ThreadGroup tg=new ThreadGroup("First Group");
Thread t1=new Thread(tg, res,"First Thread");
Thread t2=new Thread(tg, cancel, "Second Thread");
ThreadGroup tg1=new ThreadGroup(tg,"Second Group");
Thread t3=new Thread(tg1, res,"Third Thread");
Thread t4=new Thread(tg1, cancel, "Four Thread");
System.out.println("parent of tg1:" +tg1.getParent());
tg1.setMaxPriority(7);
System.out.println("Thread Group of t1:" +t1.getThreadGroup() );
System.out.println("Thread Group of t3:" +t3.getThreadGroup() );
t1.start();
t2.start();
t3.start();
t4.start();
System.out.println("No of threads active in tg="+tg.activeCount());
}
}

Output:


parent of tg1:java.lang.ThreadGroup[name=First Group,maxpri=10]

Thread Group of t1:java.lang.ThreadGroup[name=First Group,maxpri=10]
Thread Group of t3:java.lang.ThreadGroup[name=Second Group,maxpri=7]
I am reservation thread.
I am cancellation thread.
No of threads active in tg=2
I am reservation thread.
I am cancellation thread.



Wednesday, June 15, 2016

Thread Communication example in java

Thread Communication:

In some case,two or more threads should communicate with each-other.for example,a consumer thread is waiting for a producer to produce the data.when the producer thread completes production of data,then the consumer thread should take that data and use it.

Program:

/**
 * 
 */

/**
 * @author Abhinaw.Tripathi
 *
 */
class Producer extends Thread
{
 StringBuffer sb;
 boolean dataprodover=false;

 public Producer()
 {
sb=new StringBuffer();
 }

 public void run()
 {
for(int i=0;i<=10;i++)
{
sb.append(i+":");

try
{
Thread.sleep(100);
System.out.println("Appending");
}
catch (InterruptedException e)
{

e.printStackTrace();
}
}

dataprodover=true;
 }

}

class Consumer extends Thread
{
 Producer prod;
 public Consumer(Producer prod)
 {
this.prod=prod;
 }

 public void run()
 {
while(!prod.dataprodover)
try
   {
Thread.sleep(10);
}
catch (InterruptedException e)
{
e.printStackTrace();
 }
System.out.println(prod.sb);
 }
}

public class ProducerConsumerApp
{

public static void main(String[] args) {

Producer obj1=new Producer();
Consumer obj2=new Consumer(obj1);

Thread t1=new Thread(obj1);
Thread t2=new Thread(obj2);
t1.start();
t2.start();

}


}

Output:

Appending
Appending
Appending
Appending
Appending
Appending
Appending
Appending
Appending
Appending
Appending
0:1:2:3:4:5:6:7:8:9:10:

Here we can improve the efficiency of communication between threads?using 3 methods:

  • obj.notify();
  • obj.notifyAll();
  • obj.wait();
So we can use these methods inside the synchronize method.

What is difference between sleep() and wait() method?

Ans: Both sleep and wait methods are used to suspend a thread execution for a specified time.When sleep() is executed inside a synchronized block,the object is still under lock.when wait() method is executed,it breaks the synchronized block,So that the object lock is removed and it is available.

Generally,sleep() is used for making a thread to wait for some time.But wait() is used in connection with notify() or notifyAll() methods in thread communication.



Thread(Deadlock of Threads) example java

Deadlock of Threads:

When a thread has locked an object and waiting for another object to be released by another thread,and the other thread is also waiting for the first thread to release the first object,both the threads will continue waiting forever.This is called "Thread Deadlock" .

Even if we synchronize the threads ,there is possibility of other problems like deadlock.

Program:

/**
 * @author Abhinaw.Tripathi
 *
 */
class BookTicket extends Thread
{
  Object train,compartment;

  public BookTicket(Object train,Object comp)
  {
this.train=train;
this.compartment=comp;
  }

  public void run()
  {
 synchronized (train)
 {
System.out.println("BookTicket locked on train");
try
{
Thread.sleep(150);
}
catch (InterruptedException e)
{
e.printStackTrace();
}

synchronized (compartment)
{
System.out.println("Book Ticket locked on compatrment");
}

 }
  }

}

class CancelTicket extends Thread
{
   Object train,compartnment;
 
   public CancelTicket(Object train,Object comp)
   {
this.compartnment=comp;
this.train=train;
   }
 
   public void run()
   {
  synchronized (compartnment)
  {
System.out.println("Canceal Ticket locked on compartment");
try
{
Thread.sleep(200);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println("Canceal Ticket  now waiting to lock on train.....");
synchronized (train)
{
System.out.println("Cancel Ticket locked on train");
}
  }
   }
 
}

public class DeadLockApp
{
public static void main(String[] args)
{
Object train=new Object();
Object comp=new Object();

BookTicket obj1=new BookTicket(train, comp);
CancelTicket obj2=new CancelTicket(train, comp);

Thread t1=new Thread(obj1);
Thread t2=new Thread(obj2);

t1.start();
t2.start();

}


}

Output:

BookTicket locked on train
Canceal Ticket locked on compartment
Canceal Ticket  now waiting to lock on train.....

Avoiding Deadlocks in a Program:

There is specific solution for the problem of deadlocks.It depends on the logic used by the programmer.The programmer should design his program in such a way that it does not form any deadlock.

Threads examples in java

Threads

A Thread represents a separate path of execution of a group of statements.in java program,if we write a group of statements then these statements are executed by JVM one by one.This execution is called Thread. because JVM uses a thread to execute these statements.So there is always a thread running internally.Let us write a simple program to see this internal thread...

/**
 * @author Abhinaw.Tripathi
 */
public class SimpleThreadProgram {

/**
* @param args
*/
public static void main(String[] args)
{
System.out.println("Let us find current thread");
        Thread t=Thread.currentThread();
        System.out.println("Current Thread and its name is :" + t.getName());
}

}

Output:
Let us find current thread
Current Thread and its name is :main

So ,currentThread() is  a static method in Thread class and its default priority is 5 .

So which thread always runs in a java program my default?
Ans: main thread

A thread represents execution of statements .The way the statement are executed is of two types:
  1. Single Tasking
  2. Multi-tasking
Lets no be confused with the process and threads both are different things.let see how?.

Single Tasking:
A task means doing some calculation,processing ,etc.Generally, a task  involves execution of a group of statements eg. executing a program.So in single tasking environment ,only one task is given to the processor at a time.This means we are wasting a lot of processing time and microprocessor has to sit idle without any job for a long time.This is the drawback in single tasking.

Multi Tasking:

To use the processors time in an optimum way,we can give it several jobs at a time.This is called Multi-tasking.
Suppose there are 4 tasks that we want to execute.We load them into the memory.The memory is divided into 4 parts and the jobs are loaded there.Now the microprocessor has to execute them all at a time.So processor will take small time duration like a millisecond and divide this time between the number of jobs.here 4 jobs so we get 1/4 millisecond time for executing each of the processor time is called "Time-Slice".it will try to execute the job in this time frame.basically we use the processor time in an optimum way.

Multi Tasking is of two types:
  • Process-Based Multi Tasking = Several programs are executed at a time by the microprocessor.
  • Thread-Based Multi Tasking = Each thread can be imagined as an individual process that can execute a separate set of statements.
Why threads are called light-weight?

Ans: Threads are called light-weight because they utilize minimum resources of the system.This means they take less memory and less process time.

What is difference between Single and Multi Tasking ?

Ans: Executing only one job at time is called Single Tasking and Executing multiple task at a time is called Multi-Tasking.

Creating a Thread and Running it:

We all know that in java there is a main thread available already. Apart from this main thread,we can also create our own thread in a program by two ways,
  • create a class that extends Thread class 
  • implements Runnable interface
Both of the them found in java.lang package .

Eg. class MyClass extends Thread 
          or
      class MyClass implements Runnable

Now,in this class,write a run () method as

  public void run()
 {
     // statements ;
  }

By default ,this run () method is recognized and executed by a thread.

Lets take an example:

/**
 * @author Abhinaw.Tripathi
 *
 */

class MyThread extends Thread
{
public void run()
{
for(int i=0;i<=10;i++)
{
System.out.println(i);
}
}
}

public class SampleCreateThreadProg {

/**
* @param args
*/
public static void main(String[] args)
{
MyThread object=new MyThread();
Thread t=new Thread(object);
t.start();
}

}

Output:
1
2
3
4
5
6
7
8
9
10

Terminating the Thread:

A thread will terminate automatically when it comes out of run() method.now to terminate a thread on our own,we have to design our logic such as

  • Create a boolean type variable and initialize it to false;
  • boolean stop=false;
  • Let us assume that we want to terminate the thread when the user presses <Enter> key.So,when the user presses that key,make the boolean type variable as true.
  • stop=true;
public void run()
{
    if(stop==true) 
      return;
}

Lets take an example:

/**
 * @author Abhinaw.Tripathi
 *
 */
class MyThreadStop extends Thread
{
boolean stop=false;
public void run()
{
for(int i=0;i<=10;i++)
{
System.out.println(i);
if(stop)
return;
}
}
}

public class StopThreadProg 
{
public static void main(String[] args) throws IOException
{
MyThreadStop obj=new MyThreadStop();
Thread t=new Thread(obj);
t.start();
System.in.read();
obj.stop=true;
}

}

Output: 0
1
2
3
4
5
6
7
8
9
10
.... 

press <Enter> to stop the thread at any time.

What is the difference between extends thread and implement runnable ?Which one is advantageous?
Ans: extends thread and implements Runnable --both are functionally same. but when we write extends Threads,there is no scope to extend another class as multiple inheritance is not supported in java.
If we write implements Runnable ,the still there is scope to extends another class and this is advantageous for the programmer because he has a scope to extend another class too.

Which method is executed by the thread by default?
Ans:  public void run() method .

Single Tasking Using a Thread:

/**
 * @author Abhinaw.Tripathi
 *
 */
class MyThreadd implements Runnable
{
@Override
public void run() 
{
task1();
task2();
task3();
}

private void task3() 
{
System.out.println("This is task 3");
}

private void task2()
{
System.out.println("This is task 2");
}

private void task1() 
{
System.out.println("this is task 1");
}
}

public class SingleTaskingUsingThread 
{
public static void main(String[] args)
{
 MyThreadd obj=new MyThreadd();
      Thread t=new Thread(obj);
      t.start();
}
}

Output:

 this is task 1
This is task 2
This is task 3

Multi Tasking Using Threads:

/**
 * @author Abhinaw.Tripathi
 *
 */

class Threadclass implements Runnable
{

private String str;
public Threadclass(String strr) 
{
this.str=strr;
}
@Override
public void run() 
{
for(int i=0;i<10;i++)
{
System.out.println(str + ":" + i);
try 
{
Thread.sleep(5000);
catch (InterruptedException e) 
{
e.printStackTrace();
}
}
}
}

public class MultiTaskingThread
{
/**
* @param args
*/
public static void main(String[] args)
{
      Threadclass obj1=new Threadclass("Cut the Tickets");
      Threadclass obj2=new Threadclass("show the Tickets");
      Thread t1=new Thread(obj1);
      Thread t2=new Thread(obj2);
      t1.start();
      t2.start();
      
}

}

Output:

Cut the Tickets:0
show the Tickets:0
Cut the Tickets:1
show the Tickets:1
Cut the Tickets:2
show the Tickets:2
Cut the Tickets:3
show the Tickets:3
show the Tickets:4
Cut the Tickets:4
Cut the Tickets:5
show the Tickets:5
show the Tickets:6
Cut the Tickets:6
Cut the Tickets:7
show the Tickets:7
Cut the Tickets:8
show the Tickets:8
show the Tickets:9
Cut the Tickets:9