Multithreading – Java2Blog https://java2blog.com A blog on Java, Python and C++ programming languages Tue, 14 Feb 2023 11:41:06 +0000 en-US hourly 1 https://wordpress.org/?v=6.2.9 https://java2blog.com/wp-content/webpc-passthru.php?src=https://java2blog.com/wp-content/uploads/2022/09/cropped-ICON_LOGO_TRANSPARENT-32x32.png&nocache=1 Multithreading – Java2Blog https://java2blog.com 32 32 Get Thread Id in Java https://java2blog.com/get-thread-id-in-java/?utm_source=rss&utm_medium=rss&utm_campaign=get-thread-id-in-java https://java2blog.com/get-thread-id-in-java/#respond Wed, 30 Sep 2020 18:24:43 +0000 https://java2blog.com/?p=10816 In this article, we will learn to get thread id of a running thread in Java.
An Id is a unique positive number generated at the time of thread creation. This id remains unchanged during the lifetime of the thread. When a thread gets terminated its id can be used to refer another thread, but two threads can not have same id number at the same time.

To get thread id, Java Thread class provides a method getId() that returns a long type value as id number.
The syntax of the method is given below:

public long getId()

Get Thread Id in Java

In this example, we created and started a thread. After that, by using getId() method, we get thread id. See the example below.

public class Main
{   
    public static void main(String args[]) 
    {
        Thread thread = new Thread();
        thread.start();
        try {
            for (int i = 0; i < 5; i++) {
                System.out.println(i);
                Thread.sleep(500);
            }
        }catch(Exception e) {
            System.out.println(e);
        }
        // get thread id
        long id = thread.getId();
        System.out.println("Thread id : "+id);
    }
}

Output

0
1
2
3
4
Thread id : 11

Get Thread Id of Current Running Thread

If we want to get id of current runnig thread, then by using the currentThread() method we can call getId() method. See the example below.

public class Main
{   
    public static void main(String args[]) 
    {
        Thread thread = new Thread();
        thread.start();
        try {
            for (int i = 0; i < 5; i++) {
                System.out.println(i);
                Thread.sleep(500);
            }
        }catch(Exception e) {
            System.out.println(e);
        }
        // get current thread id
        long id = Thread.currentThread().getId();
        System.out.println("Thread id : "+id);
        id = thread.getId();
        System.out.println("Thread id : "+id);
    }
}

Output

0
1
2
3
4
Thread id : 1
Thread id : 11

Get Thread id of Multiple Threads

Java allows to create multiple threads, in that case we can get threat id of individual threat by calling getId() method. See the example below.

public class Main
{   
    public static void main(String args[]) 
    {
        Thread thread1 = new Thread();
        Thread thread2 = new Thread();
        Thread thread3 = new Thread();
        thread1.start();
        thread2.start();
        thread3.start();
        try {
            for (int i = 0; i < 5; i++) {
                System.out.println(i);
                Thread.sleep(500);
            }
        }catch(Exception e) {
            System.out.println(e);
        }
        // get current thread id
        long id = thread1.getId();
        System.out.println("Thread1 id : "+id);
        id = thread2.getId();
        System.out.println("Thread2 id : "+id);
        id = thread3.getId();
        System.out.println("Thread3 id : "+id);
    }
}

Output

0
1
2
3
4
Thread1 id : 11
Thread2 id : 12
Thread3 id : 13

That’s all about how to get Thread Id in Java.

]]>
https://java2blog.com/get-thread-id-in-java/feed/ 0
ArrayBlockingQueue in java https://java2blog.com/arrayblockingqueue-java/?utm_source=rss&utm_medium=rss&utm_campaign=arrayblockingqueue-java https://java2blog.com/arrayblockingqueue-java/#respond Sat, 19 Sep 2020 08:51:37 +0000 https://java2blog.com/?p=10393 In this article, we will understand the Java concurrent queue, BlockingQueue. We will then go deep into it’s one of the implementation, ArrayBlockingQueue.

What is BlockingQueue

BlockingQueue interface was introduced in Java 5 under concurrent APIs and it represents a thread-safe queue in which elements can be added to and removed from. We can have multiple threads inserting and removing elements from BlockingQueue concurrently.

The reason it is called blocking because it has the ability to block a thread from inserting an element when this queue is full and also it blocks a thread from removing an element when this queue is empty. Of course, there are different methods which decide whether to block the thread or return an exception.

ArrayBlockingQueue

The ArrayBlockingQueue implements the BlockingQueue java interface. It is a concurrent and bounded blocking queue implementation and it uses arrays to store the elements. The class provides blocking and nonblocking functions for insertion and removal of elements from the queue. By blocking it implies the functions like take() and put() will block the consumer or producer thread indefinitely unless an element is removed or inserted.

arrayblockingqueue

Features

  • It is a thread-safe implementation of the blocking queue.
  • It is a bounded queue whose size is given at the creation of an object and can’t be changed once instantiated. The queue is implemented using an array internally.
  • The elements on the ArrayBlockingQueue can be consumed in the insertion order or FIFO.
  • A null object is not allowed and it will throw an exception in case a being put on the blocking queue is null.
  • It has both blocking and nonblocking functions to place or remove elements from the queue.
  • It allows fairness policy for the Producer or Consumer threads. The fairness policy is explained in detail below

Further reading

Custom BlockingQueue in java

Custom BlockingQueue implementation in java

In this post, we will see how to create your own custom BlockingQueue. This is one of the most asked ...
BlockingQueue in java

BlockingQueue in java

BlockingQueue is introduced in java with concurrent package with ConcurrentHashMap. It is thread safe queue to put and take elements ...
Java ThreadPoolExecutor

Java ThreadPoolExecutor

Java 5 has introduced new concurrent API called Executor frameworks to make programmer life easy. It simplifies design and development ...

Constructors

The ArrayBlockingQueue has three constructors. The fairness flag set as true implies that if multiple Producer or Consumer threads are waiting on the queue either for adding or removing an element from the queue then it will ensure a FIFO order for the waiting threads else if it’s false then it doesn’t guarantee the order of the thread.

The ArrayBlockingQueue in java internally uses a Reentrant lock object instance. It also uses the lock to create two conditions notEmpty and notFull.

The notEmpty condition will allow consumers to remove elements from the queue in a threadsafe manner and will block the consumer threads in case the queue gets full.

The notFull condition will in a similar way allow producer threads to add elements in the queue in a thread-safe manner until it’s full after which it will block all producer threads.

In the third Constructor, if we pass a collection, the initial ArrayBlockingQueue will have the elements of that collection in the traversal order.

public ArrayBlockingQueue(int capacity, boolean fair)

        public ArrayBlockingQueue(int capacity) 

        ArrayBlockingQueue(int capacity, boolean fair,  Collection c)

Methods

ArrayBlockingQueue has many supported methods, we are going to list all of them and in addition, we have added the source code snippets of the actual implementation of certain functions for better understanding. The source snippets of the functions added to help in understanding how the lock and condition objects initialized in the constructor are utilized.

  1. offer(E): This function as shown below, will be adding an element into the queue at the tail, and if successful return true else if the queue capacity is reached it will return false. It’s a thread-safe method and is nonblocking i.e. if the queue is full it won’t block the producer thread but return false.

    public boolean offer(E e) {
            checkNotNull(e);
            final ReentrantLock lock = this.lock;
            lock.lock();
            try {
                if (count == items.length)
                    return false;
                else {
                    enqueue(e);
                    return true;
                }
            } finally {
                lock.unlock();
            }
        }
  2. offer(E e, long timeout, TimeUnit unit): The behavior of this function is similar to the offer(E) except in case of blocking queue being full it doesn’t quickly return false but waits till the timeout value to see if the space becomes available in the blocking queue to insert the element before it returns false.

    public boolean offer(E e, long timeout, TimeUnit unit)
            throws InterruptedException {
    
            checkNotNull(e);
            long nanos = unit.toNanos(timeout);
            final ReentrantLock lock = this.lock;
            lock.lockInterruptibly();
            try {
                while (count == items.length) {
                    if (nanos <= 0)
                        return false;
                    nanos = notFull.awaitNanos(nanos);
                }
                enqueue(e);
                return true;
            } finally {
                lock.unlock();
            }
        }
  3. put(E e): This function will insert an element into the blocking queue at the tail end and will wait indefinitely unless interrupted for insertion if the blocking queue is full.

    public void put(E e) throws InterruptedException {
            checkNotNull(e);
            final ReentrantLock lock = this.lock;
            lock.lockInterruptibly();
            try {
                while (count == items.length)
                    notFull.await();
                enqueue(e);
            } finally {
                lock.unlock();
            }
        }
    pre>
  4. add(E): This function internally uses offer(E) and behaves in the same manner except when the blocking queue is full it throws an IllegalStateException.

  5. poll(): This function removes and returns the element at the top of the blocking queue and null if the queue is empty. This is a non-blocking function.

    public E poll() {
            final ReentrantLock lock = this.lock;
            lock.lock();
            try {
                return (count == 0) ? null : dequeue();
            } finally {
                lock.unlock();
            }
        }
  6. poll(long timeout, TimeUnit unit): This function behaves just like the poll function except it will wait for the timeout parameter value if the blocking queue is empty before it attempts to fetch the element at the top of the blocking queue.

    public E poll(long timeout, TimeUnit unit) throws InterruptedException {
            long nanos = unit.toNanos(timeout);
            final ReentrantLock lock = this.lock;
            lock.lockInterruptibly();
            try {
                while (count == 0) {
                    if (nanos <= 0)
                        return null;
                    nanos = notEmpty.awaitNanos(nanos);
                }
                return dequeue();
            } finally {
                lock.unlock();
            }
        }
  7. take(): This function will return the element at the top of the blocking queue if the queue is not empty. If the blocking queue is empty then the thread calling this function will be waiting till an element is inserted into the blocking queue.

    public E take() throws InterruptedException {
            final ReentrantLock lock = this.lock;
            lock.lockInterruptibly();
            try {
                while (count == 0)
                    notEmpty.await();
                return dequeue();
            } finally {
                lock.unlock();
            }
        }
  8. peek(): This function will return the element at the top of the blocking queue without removing the element and null if the blocking queue is empty.

  9. size(): This function returns the capacity of the blocking queue

  10. remainingCapacity(): This function returns a difference between the max elements the blocking queue can hold minus the elements that are currently in the blocking queue.

  11. remove(Object o): This function removes a single instance of an element from the blocking queue if its equal to the object passed to this function. If it finds a matching element then after removal returns true else false.

  12. contains(Object o): This function returns true if an object exists on the blocking queue matching the object passed as the input parameter else false.

  13. toArray(): This function returns an Object[], which is an inorder copy of the internal array which backs the blocking queue. System.arraycopy() is used to copy the array to ensure the external modifications on the returned array don’t impact the blocking queue.

  14. clear(): This function will remove all the elements in the blocking queue in an atomic manner. This will also signal any producer threads waiting in the blocking queue after emptying the queue.

  15. drainTo(): This function will drain all the elements in the blocking queue in an atomic manner. In case your collection parameter instance and the instance on which this function called is the same then an IllegalArgumentException will be thrown. Any waiting producer threads will be signaled that the queue is empty and ready to accept new elements.

Usage Scenarios

An ArrayBlockingQueue instance can be used for resolving producer and consumer type problems when a full-fledged messaging infrastructure is not required. It can be used as a resource pool to throttle the consumers if the resources are limited.

Implementation Code

In the below unit test we create an ArrayBlockingQueue instance and start the producer and if the producer thread waits for a space created by some consumer thread. Similarly, we are also testing if the consumer thread waits for an element to be added to the queue once the queue is empty.

package main.com.kv.mt.concurrent.blockingqueue;

import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * The below code tests where the ArrayBlockingQueue makes the producer threads wait when the queue is full
 * and similarly it makes the consumer threads full if the queue is empty
 */
public class Java2BlogArrayBlockingQueue {
    public static void main(String args[]){
        final BlockingQueue blockingQueue = new ArrayBlockingQueue(5);
        final Random random = new Random();

        //producer thread keeps running until its interrupted
        Runnable producer = () -> {
            boolean isInterrupted = false;
            while(!isInterrupted) {
                try {
                    System.out.println(Thread.currentThread().getName() + " adding to queue");
                    blockingQueue.put(random.nextInt());
                    System.out.println(Thread.currentThread().getName() + " finished adding to queue");
                } catch (InterruptedException e) {
                    System.out.println(Thread.currentThread().getName() + " interrupted");
                    isInterrupted = true;
                }
            };
        };

        //consumer thread keeps running until its interrupted
        Runnable consumer = () -> {
            boolean isInterrupted = false;
            while(!isInterrupted) {
                try {
                    System.out.println(Thread.currentThread().getName() + " retrieving from queue");
                    System.out.println(Thread.currentThread().getName() + " retrieved " + blockingQueue.take() + " from queue");
                } catch (InterruptedException e) {
                    System.out.println(Thread.currentThread().getName() + " interrupted");
                    isInterrupted = true;
                }
            }
        };

        Thread producerThread = new Thread(producer);
        producerThread.setName("MyProducer");

        Thread consumerThread = new Thread(consumer);
        consumerThread.setName("MyConsumer");

        producerThread.start();

        //this code is to wait for the main thread to wait till the producer completely fills the blocking queue
        while(blockingQueue.remainingCapacity()!=0){
            try{
                Thread.sleep(5000);
            }catch (InterruptedException ie){
                System.out.println(" interrupted main thread");
            }
        }
        //This log checks the MyProducer thread state as it should be now in waiting state as the  blocking queue is full
        System.out.println("Queue is full and the MyProducer thread state : "+producerThread.getState());
        assert (Thread.State.WAITING==producerThread.getState());
        assert(producerThread.isAlive());
        // The producer thread is stopped to ensure the blocking queue becomes empty once all integers are consumed
        producerThread.interrupt();

        // now start the consumer threads
        consumerThread.start();

        //wait for the consumer to drain the blocking queue
        while(((ArrayBlockingQueue) blockingQueue).remainingCapacity()!=5){
            try{
                Thread.sleep(5000);
            }catch (InterruptedException ie){
                System.out.println(" interrupted main thread");
            }
        }

        //check the status of the consumer thread once the blocking queue is empty. it should we in waiting state
        System.out.println("Queue is empty and the MyConsumer thread state : "+consumerThread.getState());
        assert(Thread.State.WAITING==consumerThread.getState());
        assert(consumerThread.isAlive());

        //stop the consumer
        consumerThread.interrupt();
    }
}
MyProducer adding to queue
MyProducer finished adding to queue
MyProducer adding to queue
MyProducer finished adding to queue
MyProducer adding to queue
MyProducer finished adding to queue
MyProducer adding to queue
MyProducer finished adding to queue
MyProducer adding to queue
MyProducer finished adding to queue
MyProducer adding to queue
Queue is full and the MyProducer thread state : WAITING
MyProducer interrupted
MyConsumer retrieving from queue
MyConsumer retrieved -65648598 from queue
MyConsumer retrieving from queue
MyConsumer retrieved -1141421021 from queue
MyConsumer retrieving from queue
MyConsumer retrieved 1476346866 from queue
MyConsumer retrieving from queue
MyConsumer retrieved 1937023750 from queue
MyConsumer retrieving from queue
MyConsumer retrieved -1723127356 from queue
MyConsumer retrieving from queue
Queue is empty and the MyConsumer thread state : WAITING
MyConsumer interrupted

Summary

  1. We have understood what a concurrent BlockingQueue is and why it is important in a multi-threaded environment.
  2. We have also seen the implementation of BlockingQueue, i.e. ArrayBlockingQueue.
  3. We have gone through the constructors and methods of the ArrayBlockingQueue.
  4. We have implemented our own ArrayBlockingQueue and tested it with producer and consumer.
]]>
https://java2blog.com/arrayblockingqueue-java/feed/ 0
Java wait seconds or delay Java program for few secs https://java2blog.com/delay-java-program-few-secs/?utm_source=rss&utm_medium=rss&utm_campaign=delay-java-program-few-secs https://java2blog.com/delay-java-program-few-secs/#respond Wed, 11 Dec 2019 17:37:39 +0000 https://java2blog.com/?p=8158 In this post, we will see how to delay java program for few secs or wait for seconds for java program to proceed further.

We need to delay a java programs in many situation where we want to wait for some other task to finish.

There are multiple ways to delay execution of java program or wait for seconds to execute it further.


Using Thread.sleep

Sleep method causes current thread to pause for specific duration of time.We can use Thread’s class sleep static method delay execution of java program.

Here is sample code to the same.

package org.arpit.java2blog;

public class DelayFewSecondsJava {

    public static void main(String[] args) {

        System.out.println("Going for sleep for 5 secs");
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Resumed after 5 secs");

    }

}

Output:

Going for sleep for 5 secs
Resumed after 5 secs

Please note that Unit of time is milliseconds for sleep method, that’s why we have passed 5000 for 5 secs delay.

Sleep method is not always accurate as it depends on system timers and schedulers.


Using TimeUnit.XXX.sleep method

You can use java.util.concurrent.TimeUnit to sleep for specific duration of time.

For example:
To sleep for 5 mins, you can use following code

TimeUnit.MINUTES.sleep(5)

To sleep for 10 sec, you can use following code

TimeUnit.SECONDS.sleep(10)
package org.arpit.java2blog;

import java.util.concurrent.TimeUnit;

public class DelayFewSecondsJava {

    public static void main(String[] args) {

        System.out.println("Going for sleep for 10 secs");

        try {
            TimeUnit.SECONDS.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Resumed after 10 secs");
    }
}

Output:

Going for sleep for 10 secs
Resumed after 10 secs

Internally TimeUnit.SECONDS.sleep will call Thread.sleep method. Only difference is readability.


Using ScheduledExecutorService

You can also use ScheduledExecutorService which is part of executor framework. This is most precise and powerful solution to pause any java program.

I would strongly recommend to use ScheduledExecutorService in case you want to run the task every secs or few secs delay.

For example:
To run the task every second, you can use following code.

package org.arpit.java2blog;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class DelayFewSecondsJava {

    public static void main(String[] args) {

         ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
         executorService.scheduleAtFixedRate(DelayFewSecondsJava::runTask, 0, 1, TimeUnit.SECONDS);
    }

    public static void runTask()
    {
        System.out.println("Running the task each second");
    }
}

executorService.scheduleAtFixedRate(DelayFewSecondsJava::runTask, 0, 1, TimeUnit.SECONDS);
Here DelayFewSecondsJava is classname and runTask is method name of that class.

Output:

Running the task each second
Running the task each second
Running the task each second
Running the task each second

Frequently asked questions on Java wait seconds

How to wait for 5 seconds in java?

You can simply use below code to wait for 5 seconds.

Thread.sleep(5000)
or 
TimeUnit.MINUTES.sleep(5)

How to wait for 1 seconds in java?

You can simply use below code to wait for 1 seconds.

Thread.sleep(1000)
or 
TimeUnit.MINUTES.sleep(1)

How to pause for 5 seconds in java?

Pause and wait are synonyms here, so you can simply use below code to pause for 5 seconds.

Thread.sleep(5000)
or 
TimeUnit.MINUTES.sleep(5)

That’s all how to delay java program for few seconds or how to wait for seconds in java.

]]>
https://java2blog.com/delay-java-program-few-secs/feed/ 0
How to print even and odd numbers using threads in java https://java2blog.com/print-even-odd-numbers-threads-java/?utm_source=rss&utm_medium=rss&utm_campaign=print-even-odd-numbers-threads-java https://java2blog.com/print-even-odd-numbers-threads-java/#comments Wed, 29 May 2019 06:31:25 +0000 http://www.java2blog.com/?p=2406 In this post, we will see how to print even and odd numbers using threads in java.

see also: How to print sequence using 3 threads in java

Problem

You are given two threads. You need to print odd numbers using one thread and even numbers using another thread.You need to print in natural order up to MAX.
For example:
If MAX is 10, you need to print:

1 2 3 4 5 6 7 8 9 10

So 1 3 5 7 9 will be printed by odd thread
2 4 6 8 10 will be printed by even thread.

Solution 1

We will use wait and notify to solve how to print even and odd numbers using threads in java.

  • Use a variable called boolean odd. If you want to print odd number, it’s value should be true and vice versa for even number.
  • Create two methods printOdd() and printEven(), one will print odd numbers and other will print even numbers.
  • Create two threads, t2 for odd and t1 for even.
  • t1 will call printEven() method and t2 will call printOdd() method simultaneously.
  • If boolean odd is true in printEven() method, t1 will wait.
  • If boolean odd is false in printOdd() method, t2 will wait.

Print even and odd numbers using threads in java

package org.arpit.java2blog;

public class OddEvenPrintMain {

    boolean odd;
    int count = 1;
    int MAX = 20;

    public void printOdd() {
        synchronized (this) {
            while (count < MAX) {
                System.out.println("Checking odd loop");

                while (!odd) {
                    try {
                        System.out.println("Odd waiting : " + count);
                        wait();
                        System.out.println("Notified odd :" + count);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                System.out.println("Odd Thread :" + count);
                count++;
                odd = false;
                notify();
            }
        }
    }

    public void printEven() {

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }
        synchronized (this) {
            while (count < MAX) {
                System.out.println("Checking even loop");

                while (odd) {
                    try {
                        System.out.println("Even waiting: " + count);
                        wait();
                        System.out.println("Notified even:" + count);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("Even thread :" + count);
                count++;
                odd = true;
                notify();

            }
        }
    }

    public static void main(String[] args) {

        OddEvenPrintMain oep = new OddEvenPrintMain();
        oep.odd = true;
        Thread t1 = new Thread(new Runnable() {

            @Override
            public void run() {
                oep.printEven();

            }
        });
        Thread t2 = new Thread(new Runnable() {

            @Override
            public void run() {
                oep.printOdd();

            }
        });

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

        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}

When you run above program, you will get below output:

Checking odd loop
Odd Thread :1
Checking odd loop
Odd waiting : 2
Checking even loop
Even thread :2
Checking even loop
Even waiting: 3
Notified odd :3
Odd Thread :3
Checking odd loop
Odd waiting : 4
Notified even:4
Even thread :4
Checking even loop
Even waiting: 5
Notified odd :5
Odd Thread :5
Checking odd loop
Odd waiting : 6
Notified even:6
Even thread :6
Checking even loop
Even waiting: 7
Notified odd :7
Odd Thread :7
Checking odd loop
Odd waiting : 8
Notified even:8
Even thread :8
Checking even loop
Even waiting: 9
Notified odd :9
Odd Thread :9
Checking odd loop
Odd waiting : 10
Notified even:10
Even thread :10
Checking even loop
Even waiting: 11
Notified odd :11
Odd Thread :11
Checking odd loop
Odd waiting : 12
Notified even:12
Even thread :12
Checking even loop
Even waiting: 13
Notified odd :13
Odd Thread :13
Checking odd loop
Odd waiting : 14
Notified even:14
Even thread :14
Checking even loop
Even waiting: 15
Notified odd :15
Odd Thread :15
Checking odd loop
Odd waiting : 16
Notified even:16
Even thread :16
Checking even loop
Even waiting: 17
Notified odd :17
Odd Thread :17
Checking odd loop
Odd waiting : 18
Notified even:18
Even thread :18
Checking even loop
Even waiting: 19
Notified odd :19
Odd Thread :19
Notified even:20
Even thread :20

If you observe output, you should be able to understand above program.

Let me try to explain first few lines:
Checking odd loop : t2 Checks for while condition in printOdd() method
Odd Thread :1 : t2 Prints the count ,increment it by one and make odd=false
Checking odd loop : Checks for while condition in printOdd() method
Odd waiting : 2: Since odd=false  now, t2 will wait and releases the lock
Checking even loop: t1 checks for while condition in printEven() method
Even thread :2 : t1 prints the count,increment it by one and make odd=true
Checking even loop: t1 checks for while condition in printEven() method
Even waiting: 3: Since odd=true now, t1 will wait and releases the lock
Notified odd :3 : Since we have called notify() when we were printing Even thread 2, it will notify t2.

All other steps will follow.

Solution 2: Using remainder

You can use concept of remainder here.

  • If number%2==1 then Odd will print the number and increment it else will go in the wait state.
  • If number%2==0 then Even will print the number and increment it else will go in the wait state.

Let’s check with the help of example.

Create a class named OddEvenRunnable and implement Runnable interface.

Create a class named OddEvenRunnable. It will implement Runnable interface.

public class OddEvenRunnable implements Runnable{

    public int PRINT_NUMBERS_UPTO=10;
    static int  number=1;
    int remainder;
    static Object lock=new Object();

    OddEvenRunnable(int remainder)
    {
        this.remainder=remainder;
    }

    @Override
    public void run() {
        while (number < PRINT_NUMBERS_UPTO) {
            synchronized (lock) {
                while (number % 2 != remainder) { // wait for numbers other than remainder
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println(Thread.currentThread().getName() + " " + number);
                number++;
                lock.notifyAll();
            }
        }
    }
}

Create Main class named "PrintOddEvenMain"

public class PrintOddEvenMain {
    public static void main(String[] args) {

        OddEvenRunnable oddRunnable=new OddEvenRunnable(1);
        OddEvenRunnable evenRunnable=new OddEvenRunnable(0);

        Thread t1=new Thread(oddRunnable,"Odd");
        Thread t2=new Thread(evenRunnable,"Even");

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

    }
}

When you run above program, you will get below output

Odd 1
Even 2
Odd 3
Even 4
Odd 5
Even 6
Odd 7
Even 8
Odd 9
Even 10

This is all about printing even and odd numbers using threads in java. Please comment if the explanation is not very clear.

You may also like:

]]>
https://java2blog.com/print-even-odd-numbers-threads-java/feed/ 18
Why wait(), notify() And notifyAll() methods are in Object Class https://java2blog.com/why-wait-notify-notifyall-methods-object-class/?utm_source=rss&utm_medium=rss&utm_campaign=why-wait-notify-notifyall-methods-object-class https://java2blog.com/why-wait-notify-notifyall-methods-object-class/#comments Mon, 22 Oct 2018 16:29:51 +0000 https://java2blog.com/?p=6735 In this post, we will see why wait(), notify() And notifyAll() methods are in Object Class And Not in Thread Class.

This is one of the most asked java multithreading interview questions.

You might know that wait(), notify() And notifyAll() Methods are in Object class and do you know the reason for the same?

Let’s discuss why wait(), notify() And notifyAll() Methods Are in Object Class.

In Java, thread waits on monitor assigned to the object and when you want to send a signal to another thread who is waiting for the same monitor, you call notify() method to wake one thread and notifyAll() to wake up all the threads.

If wait, notify and notifyAll method are in thread class, then each thread should be aware of the status of another thread.

For example: Let’s say you have two threads, T1 and T2. Now T1 must know that T2 was waiting for this particular resource which I have just freed because T1 will need to call T2.notify().

In Java, the object itself is shared among the threads and facilitates inter-thread communication. Threads have no specific knowledge of each other. They can run asynchronously and are independent. They just run, lock, wait and get notified. They do not need to know about the status of other threads. They just need to call notify method on an object, so whomever thread is waiting on that resource will be notified.

As stated before,

  • When you call wait() method on the object, then it gives up monitor and go to sleep
  • When you call notify() method, then the single thread which is waiting for the object’s monitor will be notified.

Hence wait, notify() And notifyAll() work at object’s monitor level. If thread which is currently holding the monitor, wants to give up the monitor then it will call wait method on the object and if it want to notify other thread, then it will call notify method on the object.

Shared objects allow threads to communicate by calling wait(), notify() And notifyAll() Methods, so these methods are in the object class.

That’s all about why wait(), notify() And notifyAll() methods Are in Object Class And Not in Thread Class.

]]>
https://java2blog.com/why-wait-notify-notifyall-methods-object-class/feed/ 1
Custom BlockingQueue implementation in java https://java2blog.com/custom-blockingqueue-implementation-java/?utm_source=rss&utm_medium=rss&utm_campaign=custom-blockingqueue-implementation-java https://java2blog.com/custom-blockingqueue-implementation-java/#respond Tue, 16 Oct 2018 18:16:20 +0000 https://java2blog.com/?p=6664 In this post, we will see how to create your own custom BlockingQueue.

This is one of the most asked java interview questions. You need to implement your own BlockingQueue. This question helps interviewer to get your understanding of multithreading concepts.

Here is simple implementation of BlockingQueue.

  • We will use array to store elements in BlockingQueue internally. Size of this array defines maximum number of  elements that can reside in BlockingQueue at a time.
  • We will use lock and conditions objects to create custom BlockingQueue.
  • While putting the element in the queue, if the queue is full, then the producer will wait for queue to empty.
  • While consuming element from the queue, if the queue is empty then the consumer will wait for the queue to get filled.

Create a class named CustomBlockingQueue.java

package org.arpit.java2blog;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class CustomBlockingQueue {

    final Lock lock = new ReentrantLock();

    // Conditions
    final Condition produceCond  = lock.newCondition(); 
    final Condition consumeCond = lock.newCondition(); 

    // Array to store element for CustomBlockingQueue
    final Object[] array = new Object[6];
    int putIndex, takeIndex;
    int count;

    public void put(Object x) throws InterruptedException {

        lock.lock();
        try {
            while (count == array.length){
                // Queue is full, producers need to wait
                produceCond.await();
            }

            array[putIndex] = x;
            System.out.println("Producing - " + x);
            putIndex++;
            if (putIndex == array.length){
                putIndex = 0;
            }
            // Increment the count for the array
            ++count;
            consumeCond.signal();
        } finally {
            lock.unlock();
        }
    }

    public Object take() throws InterruptedException {
        lock.lock();
        try {
            while (count == 0){
                // Queue is empty, consumers need to wait
                consumeCond.await();
            }
            Object x = array[takeIndex];
            System.out.println("Consuming - " + x);
            takeIndex++;
            if (takeIndex == array.length){
                takeIndex = 0;
            }
            // reduce the count for the array
            --count;
            // send signal producer
            produceCond.signal();
            return x;
        } finally {
            lock.unlock();
        }
    }
}

Create another main class which will use above CustomBLockingQueue.

package org.arpit.java2blog;

public class CustomBlockingQueueMain {

    public static void main(String[] args) {
        CustomBlockingQueue customBlockingQueue = new CustomBlockingQueue();
        // Creating producer and consumer threads
        Thread producer = new Thread(new Producer(customBlockingQueue));
        Thread consumer = new Thread(new Consumer(customBlockingQueue)); 

        producer.start();
        consumer.start();
    }
}

class Producer implements Runnable {

    private CustomBlockingQueue customBlockingQueue;

    public Producer(CustomBlockingQueue customBlockingQueue){
        this.customBlockingQueue = customBlockingQueue;
    }
    @Override
    public void run() {
        for (int i = 1; i <= 10; i++) {
            try {
                customBlockingQueue.put(i);                            
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}

class Consumer implements Runnable {
    private CustomBlockingQueue customBlockingQueue;

    public Consumer(CustomBlockingQueue customBlockingQueue){
        this.customBlockingQueue = customBlockingQueue;
    }
    @Override
    public void run() {
        for (int i = 1; i <= 10; i++) {
            try {
                customBlockingQueue.take();               
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}

We have created two Runnable classes, one for producer and another for consumer and created two threads using these runnables.

Producing – 1
Producing – 2
Producing – 3
Producing – 4
Producing – 5
Producing – 6
Consuming – 1
Consuming – 2
Consuming – 3
Consuming – 4
Consuming – 5
Consuming – 6
Producing – 7
Producing – 8
Producing – 9
Producing – 10
Consuming – 7
Consuming – 8
Consuming – 9
Consuming – 10

Output may vary for you but there can be only 6 elements at a time in the CustomBlockingQueue.
That’s all about Custom BlockingQueue implementation in java

]]>
https://java2blog.com/custom-blockingqueue-implementation-java/feed/ 0
Difference between Runnable and Callable in java https://java2blog.com/difference-runnable-callable-java/?utm_source=rss&utm_medium=rss&utm_campaign=difference-runnable-callable-java https://java2blog.com/difference-runnable-callable-java/#comments Fri, 15 Dec 2017 19:50:30 +0000 https://www.java2blog.com/?p=4351 Runnable and Callable interface both are used in the multithreading environment.Callable is available in java.util.concurrent.Callable package and Runnable in java.lang.Thread.

Difference between Runnable and Callable interface in java

  • Runnable was introduced in java 1.0 version While Callable is an extended version of Runnable and introduced in java 1.5 to address the limitation of Runnable.
  • Runnable does not return any value; its return type is void, while Callable have a return type.So, after completion of task, we can get the result using get() method of Future class. Future class has various methods such as get(), cancel() and isDone() by which you can get or perform various operations with respect to tasks.Ex:
    //Runnable interface method's run method has return type as void
    public void run()
    {
    
    }
    
    //Callable interface method's call method has return type as generic V
    V call() throws Exception;
    {
    
    }
    Callable is a generic interface means implementing class will decide the type of value it will return.
  • Runnable does not throws checked exception while Callable throws checked exception(i.e exception that are checked at compile time)so, at compile time we can identify the error.
  • In Runnable, we override run() method, while in Callable, we need to override call() method.
  • Runnable is used when we don’t want any return value after completion of task for ex: logging, while Callable is used  when we want to get a result of the computation.
  • First, we create the instance of class which has implemented Runnable interface and after that create instance of Thread class and then pass the object of Runnable class as parameter in Thread class.
    Runnable Class rc=new RunnableClass();
    Thread t=new Thread(rc);
    t.start();
    In case of Callable,we can not pass Callable into Thread to execute, so we need to use ExecutorService to execute Callable object.
]]>
https://java2blog.com/difference-runnable-callable-java/feed/ 1
Print Numbers Using Multiple Threads in Java https://java2blog.com/print-sequence-3-threads-java/?utm_source=rss&utm_medium=rss&utm_campaign=print-sequence-3-threads-java https://java2blog.com/print-sequence-3-threads-java/#comments Thu, 16 Nov 2017 18:55:28 +0000 https://www.java2blog.com/?p=4669 In this post, we will see how to print numbers using multiple threads in java.It is similar to printing odd-even numbers using two threads in java.

Problem

You are given 3 threads. You need to print sequence using these 3 threads.You need to print in natural order up to MAX.

For example:
Let’s say you have 3 threads. T1,T2 and T3.
If MAX is 10, you need to print:

T1 1
T2 2
T3 3
T1 4
T2 5
T3 6
T1 7
T2 8
T3 9
T1 10

Solution

We will use concept of remainder here.

  • If number%3==1 then T1 will print the number and increment it else will go in the wait state.
  • If number%3==2 then T2 will print the number and increment it else will go in the wait state.
  • If number%3==0 then T3 will print the number and increment it else will go in the wait state.

Let me provide simple program for it.
Let’s create a class named "PrintSequenceRunnable" which will implement the Runnable interface.

public class PrintSequenceRunnable implements Runnable{

    public int PRINT_NUMBERS_UPTO=10;
    static int  number=1;
    int remainder;
    static Object lock=new Object();

    PrintSequenceRunnable(int remainder)
    {
        this.remainder=remainder;
    }

    @Override
    public void run() {
        while (number < PRINT_NUMBERS_UPTO-1) {
            synchronized (lock) {
                while (number % 3 != remainder) { // wait for numbers other than remainder
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println(Thread.currentThread().getName() + " " + number);
                number++;
                lock.notifyAll();
            }
        }
    }
}

Let’s create a class named "PrintThreadsSequentiallyMain" which will implement the Runnable interface.

public class PrintThreadsSequentiallyMain {

    public static void main(String[] args) {

        PrintSequenceRunnable runnable1=new PrintSequenceRunnable(1);
        PrintSequenceRunnable runnable2=new PrintSequenceRunnable(2);
        PrintSequenceRunnable runnable3=new PrintSequenceRunnable(0);

        Thread t1=new Thread(runnable1,"T1");
        Thread t2=new Thread(runnable2,"T2");
        Thread t3=new Thread(runnable3,"T3");

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

When you run above program, you will get below output.

T1 1
T2 2
T3 3
T1 4
T2 5
T3 6
T1 7
T2 8
T3 9
T1 10

That’s all about printing numbers using multiple threads in java.

]]>
https://java2blog.com/print-sequence-3-threads-java/feed/ 1
Java Runnable example https://java2blog.com/java-runnable-example/?utm_source=rss&utm_medium=rss&utm_campaign=java-runnable-example https://java2blog.com/java-runnable-example/#respond Sun, 24 Sep 2017 08:36:37 +0000 https://www.java2blog.com/?p=4032 In this post, we will see Java Runnable example.
As you might know, there are two ways of creating threads in java.

  • Extending thread class
  • Implementing Runnable interface.

As you can extend only one class in java, it is not possible to extend any other class if a class extends thread class.You can also implement Runnable interface and then pass it Thread class constructor. As class can implement multiple interfaces in java, it is a good idea to create thread via implementing Runnable interface.

Java Runnable example

Create a class named SampleRunnable which will implement Runnable interface. When you implement Runnable interface, you need to provide an implementation for run method.

package org.arpit.java2blog;

public class SampleRunnable implements Runnable{

    public void run() {
        System.out.println("In run method");
    }
}

Create Main class named "JavaRunnableMain"

package org.arpit.java2blog;

public class JavaRunnableMain {

    public static void main(String[] args) {
        Runnable runnable=new SampleRunnable();
        // Pass Runnable to constructor of thread class
        Thread t=new Thread(runnable);
        t.start();
    }
}

When you run above program, you will get below output

In Run method

Java Anonymous Runnable example

You can also pass Runnable to Thread class by providing Anonymous Runnable implementation. You do not need to create separate class to implement run method.You can simply create Anonymous class and provide the implementation of run method.

package org.arpit.java2blog;

public class JavaAnoynomousRunnableMain {

    public static void main(String[] args) {
        Thread t=new Thread(new Runnable() {

            @Override
            public void run() {
                System.out.println("In Run method");
            }
        });
        t.start();
    }
}

When you run above program, you will get below output

In Run method

Java 8 Runnable example

As Runnable is the functional interface, you can simply use the lambda expression to provide implementation of Runnable interface instead of creating Anonymous Runnable as above.

package org.arpit.java2blog;

public class Java8RunnableMain {

    public static void main(String[] args) {
        Thread t=new Thread(()->System.out.println("In Run method"));
        t.start();
    }
}

When you run above program, you will get below output

In Run method

That’s all about Java Runnable example.

]]>
https://java2blog.com/java-runnable-example/feed/ 0