threads – Programmerbay https://programmerbay.com A Tech Bay for Tech Savvy Tue, 06 Oct 2020 05:19:14 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 https://programmerbay.com/wp-content/uploads/2019/09/cropped-without-transparent-32x32.jpg threads – Programmerbay https://programmerbay.com 32 32 Difference between join() and yield() in Multithreading https://programmerbay.com/difference-between-join-and-yield-mulithreading/ https://programmerbay.com/difference-between-join-and-yield-mulithreading/#respond Thu, 27 Feb 2020 13:12:45 +0000 https://programmerbay.com/?p=6149 Difference between join() and yield() in Tabular form
Join MethodYield Method
It ensures a calling thread to get terminated first and then after further execution is proceeded by other thread instanceIt simply makes other threads having same priority to do their task
It puts other threads to suspended state, till the thread on which the join() call is finishedIt moves a thread from running to runnable
It allows us to provide threshold time It doesn't, totally depends on thread Schedular
Priority doesn't matterApplies on same priority thread

Join() Method

Join method ensures termination or completion of a thread on which it is called. So, that other threads can join the calling thread as and when it dies.

The statement after the join() won’t be executed by current thread instance until the thread on which it is invoked finishes its task. However, it is also possible to mention maximum time to which extent to wait.

Java program Example:

class ThreadExample extends Thread{
    @Override
    public void run() {
        System.out.println("Child thread is printing");
       for(int i=0;i<10;i++)
       {
           System.out.println(i);
       }
        try {
            sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
public class Main {

    public static void main(String[] args) throws InterruptedException {
ThreadExample thread1 = new ThreadExample();
thread1.start();

        thread1.join();
        System.out.println("I will wait for child thread to join me");
        System.out.println("Now Main thread is executing");
    }
}

Output

Child thread is printing
0
1
2
3
4
5
6
7
8
9
I will wait for child thread to join me
Now Main thread is executing

 

yield() Method

Yield method simply let other threads of same priority of the calling thread to finish their task.

In other words, It tells the thread scheduler that the thread who actually called the yield() is willing to wait and allow other threads having same priority to execute their task.

Java program Example:

class ThreadExample extends Thread{
    @Override
    public void run() {


       for(int i=0;i<10;i++)
       {
           yield();
           System.out.println("I am child "+Thread.currentThread().getPriority());
       }

    }
}
public class Main {

    public static void main(String[] args) {
ThreadExample thread1 = new ThreadExample();
thread1.start();

System.out.println(" Main thread is executing");
        for(int i=0;i<10;i++)
        {

            System.out.println("I am Main "+Thread.currentThread().getPriority());
        }
    }
}

Output:

Main thread is executing
 I am Main 5
 I am child 5
 I am Main 5
 I am child 5
 I am Main 5
 I am child 5
 I am Main 5
 I am child 5
 I am Main 5
 I am child 5
 I am Main 5
 I am child 5
 I am Main 5
 I am child 5
 I am Main 5
 I am child 5
 I am Main 5
 I am child 5
 I am Main 5
 I am child 5

 

]]>
https://programmerbay.com/difference-between-join-and-yield-mulithreading/feed/ 0
Explain Multithreading in Java with Example https://programmerbay.com/multithreading-in-java-with-example/ Wed, 22 Jan 2020 05:47:37 +0000 https://programmerbay.com/?p=5931 Another important feature of Java is support for Multithreading programming. It can be viewed as multitasking at the programmatic level. It reduces the program execution time and helps in achieving an efficient program.

In a program, there may be various functionalities which are independent of each other, having unique separate paths. Meaning, these functionalities can be carried out concurrently at the same time span.

This can be achieved through threads, by framing each function or task as a single thread makes parallel execution possible. A thread is nothing, but the smallest executable code without dependency.

Multthreading can be defined as a program having two or more threads performing various independent tasks concurrently

Thread

A thread is the smallest independent part of a program that can execute independently from other threads. It is the smallest piece of executable code that uses shared memory space and other resources with other threads to perform its task.

A single thread called the main() thread can always be found in the newly created program and accountable for the creation and termination of other threads.

Important Notes:

– It utilizes the processor and doesn’t let it sit idle
– Multithreading can be used in a various scenario such as maintaining the responsiveness of application, in the long run, parallel execution of two different tasks, handling client’s request in case of the Web application and more
– It givesĀ  an efficient program
– A thread is also known as lightweight processes

– Thread Priorities play an important role in controlling the thread execution. A thread priority ranges from 1 to 10. 1 represents the lowest priorities and 10 highest. By default, 5 is assigned to a thread as its priority.

Life Cycle of a thread

final thread lifecycle

There are various phases or stages in the lifecycle of a thread. A thread can have multiple states, new, runnable,running, blocked and terminated are the examples. These are the following:-

New: When an instance of a thread is created then it is said to be a New thread is born.

Runnable: When a thread is ready to perform its tasks but the processor hasn’t allocated to it.

Running: When a thread gets the processor and starts executing its tasks.

Blocked: A thread is said to be blocked when it waits for resource or an event to occur.

Terminated: A thread gets terminated when it completes its assigned task or is forcefully stopped. It can’t be resumed from this state.

Click here for a detailed article on Java Thread Lifecycle.

Synchronization

To control asynchronous behavior, synchronization is used. Synchronization can be defined as a scenario where two or more threads try to access a shared resource at the same time. It can be resolved by ‘Monitor’ which can be thought of as a small box having capacity to hold a single thread. So, when a thread gets into the monitor ( area), all other threads require to wait until entered thread performs its task and comes out.

A simple Java program to create a thread

class MyFirstThread extends Thread{

@Override
public void run()
{
    int i;
for(i=0;i<3;i++)
{
System.out.println("I am First Thread");

}

}
}
class MySecondThread extends Thread{
@Override
public void run()
{
    int i;
for(i=0;i<3;i++)
{
System.out.println("I am Second Thread");

}

}
}
public class ThreadProgram {

    public static void main(String[] args) {
 MyFirstThread Thread1 = new MyFirstThread();
  MySecondThread Thread2 = new MySecondThread();
  
 Thread1.start();
 Thread2.start();
    }
    
}

Output:

thread output

However, a thread can be created either by implementing Runnable Interface or by extending Thread class. [ Click here to learn]

]]>