Java Threads

SyntaxHighlighter.all();

Thread is a light weight process. An instance of java.lang.Thread is called thread in java. JVM calls main thread which calls main method.

When a thread is created corresponding stack area is created. Objects are made in heap area.

Different threads are executed in same memory address whereas different process utilize different memory allocation.

Advantages of multi-threaded application

a) Use less resources.

b) Inter-thread communication is easy.

Multithreading is used when we want to perform multiple task in a single application.

There are 2 ways to create Thread in Java

1) Implement Runnable Interface

2) Extend Thread Class

Method in Runnable Interface

public void run()

General steps to follow for creating a thread based app

1) Create the task.

2) Create the worker.

3) Assign the task to the worker.

4) Say start to the worker.

5) Worker will start performing the task.

6) When task will come to end the worker will die.

class Task implements Runnable

{

    public void run()

   {

       // define the task

   }

}

class User

{

    public static void main(String[] args)

    {

        Task t = new Task();

        Thread worker = new Thread();

        worker.start();
    }
}

Life Cycle of Thread

new Thread –> Ready to run –> Running –> Dead

Ready to run  –> Blocked State –> Ready to run (sleep(), join(), IO blocked state)

Priorities static variables in Thread class :-

MIN_PRIORITY

NORM_PRIORITY – default

MAX_PRIORITY

Priority is set always before start() method.

setPriority() – maximum number of CPU cycles to be given to the thread.

join() – method is used if parent or any peer thread has to wait for another thread.

Synchronization 

Synchronization  is used to achieve expected output in case when more than one thread are running in parallel. Multiple running threads can corrupt data of one another.

For ex –

class SyncTest implements Runnable

{
    public void run()

    {

        show();
    }

    synchronize void show()

    {

        for(int x=1;x<=5;x++)

        {

            System.out.println(Thread.currentThread().getName());

            System.out.println("["+"hi buddy");

            try

            {

                Thread.sleep();

            }
            catch(InterruptedException e) 
            { System.out.println(e);  }

            System.out.printn("]");
        }
    }    
}
public class SyncMethod

{

    public static void main(String[] args)

    {

        Runnable nr = new SyncTest();

        Thread one = new Thread(nr);

        Thread two = new Thread(nr);

        Thread three = new Thread(nr);

        one.setName("ABC");

        two.setName("XYZ");

        three.setName("PQR");

        one.start(); two.start(); three.start();
    }
}

If two methods are synchronized in the same class than only one thread can enter one synchronized method at a time. If one thread completes its work and releases the lock than only other thread can enter the method.

Static method get lock from class. If one get the lock other static methods will also be locked.

class Task

{

    synchronized static void method1() -> class lock is activated

    { //task t1}

    static void method2()

    { //task t2}

    // t3 will not be able to get the lock until class lock released by t1

    synchronized static void method3()

    {}

}

If we do not have source code of Task class we can use synchronized block to synchronize various methods.

Task tk = new Task();

synchronized(tk); // called when object is created

{

    tk.method1();

    tk.method2();

}

Actual meaning of Class lock

java.lang.Class object is created when class is loaded in JVM and that object represent our class.

Note

a) Class lock works on non-static method.

b) Lock our class can work on our block.

c) In synchronized block only calling is synchronized nor the method.

Threads are categorized into

1) User Thread

2) Daemon Thread

Daemon Threads are created to serve user threads if no user thread is there then daemon thread will finish.

Method used – setDaemon(bool);

For a thread we can set daemon before the thread is started. Garbage collector is an example of daemon thread.

The best approach for creating thread is  implementing Runnable interface because

a) We cannot extend more than one class.

b) Many methods will be inherited in our class which are not necessary.

Performing Inter-Thread Communication

Methods such as wait(), notify() and notifyAll() in Object class are used in inter thread communication.

Ex – Producer Consumer problem

class Inventory

{

    boolean flag = false;

    public synchronized void itemProduce(int i)

    {

        if(flag)

        {

            try

            {

                wait();

            }catch(Exception e) {}

        }

        System.out.println(i+"is going to produce..");

        try

        {

            Thread.sleep(1000);

        }catch(Exception e) {}

        System.out.println(i+"is produced..");

        flag = true;

        notify();
    }

    public synchronized void itemConsume(int i)

    {

        if(flag)

        {
            try 
            {
                wait();
            }
            catch(Exception e) {}
        }

        try
        {
            Thread.sleep(1000);
        } catch(Exception e) {}

        System.out.println(i+"item is consumed");

        flag = false;

        notify();
    }
}

class ProducerThread extends Thread
{
    Inventory br;

    ProducerThread(Inventory br)

    {
        this.br = br;
    }

    public void run()

    {
        for(int i=0;i<5;i++)

        {
            br.itemProduce(i);
        }
    }
}

class ConsumerThread extends Thread

{
    Inventory br;

    ConsumerThread(Inventory br)

    {
        this.br = br;
    }

    public void run()

    {
        for(int i=0;i<5;i++)

        {
            br.itemConsume(i);
        }
    }
}

class ProConProblem

{
    public static void main(String[] args)

    {
        System.out.println("Enter main");

        Inventory br = new Inventory();

        ProducerThread pt = new ProducerThread(br);

        ConsumerThread ct = new ConsumerThread(br);

        ct.start();

        pt.start();

        System.out.println("Exit main");
    }
}

About neer1304

An INTJ Curious Geek
This entry was posted in Multi-Threading and tagged , . Bookmark the permalink.

Leave a comment