Pages

Showing posts with label Threads. Show all posts
Showing posts with label Threads. Show all posts

Sunday, September 1, 2024

Java Thread.join() Examples to Wait for Another Thread

1. Introduction


In this tutorial, We'll learn how to use Thread.join() method in java. And also how to join the multiple threads at one place after completing the execution of all threads or one thread or any other threads.

join() method is part of the Thread class and it is part of the java.lang package. All the classes in java.lang package is not needed to add import statements. So, directly you can use it in the programs. join() is mainly used to sleep or wait the current thread until completion of another thread execution.

Similar to the wait() and notify(), join() also widely used in the thread intercommunication.

2. Thread.join() Syntax


below is the syntax from Thread API. join() method is an overloaded method so we should be careful which method should be used.

public final void join() throws InterruptedException

public final void join(long millis) throws InterruptedException

public final void join(long millis, int nanos) throws InterruptedException


Java 8 String API also has join() method.

Tuesday, December 1, 2020

How To Create A Thread Using Lambda Expressions In Java 8 and Using Runnable With Lambda?

 1. Overview

In this tutorial, we'll learn how to create a thread using lambda expression in java 8 and beyond versions.

Lambda expressions are newly added concept in the JDK 1.8 version and that introduced the functional programming concepts such as assigning the method to the variable.

Important point is that we can directly implementation for the abstract method of interface with java 8 lambda instead of overriding the method by implementing the interface.

How To Create A Thread Using Lambda Expressions In Java 8?


2. Example To Create New Thread Via Runnable Using Lambda in Java 8

In the below program, we are going to create the Thread and implementing the Runnable interface run() method using Lambda Expression.

By using Lambda, we can skip the implements Runnable interface and overriding the run() method which holds the core thread logic.

If you are new to java 8 lambda, you can read the complete set of rules to Lambda Expressions.

And also we can avoid new Runnable() and implementing the run() method using lamdba. Because, once you start writing the code using java 8 then compiler knows that you are using Function Interface Runnable which has only run() method.

So when you pass Runnable lambda to Thread constructor, it treats as passing implementation of Runnable interface with run() method.

Next, Look at the below example program to create a java thread via runnable using lambda expression


package com.javaprogramto.threads.java8;

public class CreateThreadLambda {

	public static void main(String[] args) {

		// Thread creation using java 8 lambda using runnable
		Thread evenNumberThread = new Thread(() -> {
			
			// this logic is implementation of run() method to print only even numbers
			for (int i = 0; i < 20; i++) {
				if (i % 2 == 0) {
					System.out.println("Even Number Thread : "+i);
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		});

		// starting the thread
		evenNumberThread.start();
		
		// Printing the odd numbers from main thread.
		for (int i = 0; i < 20; i++) {
			if (i % 2 == 1) {
				System.out.println("Odd Number Thread : "+i);
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}

	}
}
 

Output:

Even Number Thread : 0
Odd Number Thread : 1
Odd Number Thread : 3
Even Number Thread : 2
Odd Number Thread : 5
Even Number Thread : 4
Even Number Thread : 6
Odd Number Thread : 7
Odd Number Thread : 9
Even Number Thread : 8
Odd Number Thread : 11
Even Number Thread : 10
Odd Number Thread : 13
Even Number Thread : 12
Even Number Thread : 14
Odd Number Thread : 15
Even Number Thread : 16
Odd Number Thread : 17
Even Number Thread : 18
Odd Number Thread : 19
 

3. Conclusion

In this article, we've seen how to create a new thread using lambda java 8 with example program to print even and odd number in unordered.

GitHub

Runnable API

Creating a thread using Thread class and Runnable Interface

Wednesday, August 5, 2020

How to Add delay in Java for sometime?

1. Overview


In this article, You'll learn how to delay the code execution for some seconds or minutes in java. This quite simple and easy to force the code to sleep or pause for some time and do the remaining execution or waiting for another task to complete.

You might be seeing this is needed when you have any failures or connectivity issues in the application then immediately you don't want to execute tasks. So, You must have to wait for sometime before running the same task.

This is a common use case in every realtime application.

Let us explore the different ways to do the delay in java.

How do I make a delay in Java? Pausing Execution with Sleep

Thursday, July 9, 2020

Create Thread without extending Thread and implementing Runnable

1. Introduction


In this quick article, You'll learn how to create a thread without extending the Thread class and implementing the Runnable interface.

Create Thread without extending Thread and implementing Runnable


Saturday, July 4, 2020

How to create a thread without implementing the Runnable interface in Java?

1. Introduction


In this tutorial, You'll learn how to create a thread without implementing the Runnable interface in Java.

Thread is a lightweight process and every program in java starts in a thread. So by default when you run the main program that has the main() method, JVM will create a thread to run the main program. The default thread is called "main thread".

Additionally, Java supports multithreading which means you can one or more threads at the same time.

Let us see the different ways to create a thread in java using Anonymous implementation for the Runnable interface.

How to create a thread without implementing the Runnable interface in Java?


Friday, January 24, 2020

Java Thread interrupt() VS interrupted() VS isInterrupted() Examples

1. Introduction


In this article, we will go through the thread class methods interrupt(), interrupted() and isInterrupted(). All these methods are looking for the same usage and context but they do different jobs in little differently.

Syntax:

public void interrupt()
public static boolean interrupted()
public boolean isInterrupted()

This method can be used to kill the thread using interrupt() method.

Java Thread interrupt() VS interrupted() VS isInterrupted() Examples


Wednesday, January 22, 2020

Matrix Multiplication with Java Threads - Optimized Code (Parallel)

1. Introduction


In this tutorial, We will write the code to matrix multiplication in java using the normal approach and multiple threads in parallel. This question will be asked in many interview program questions to see whether can you improve the performance for large matrixes.

We'll implement the programs for both cases.

Basic Matrix Multiplication Ref

Matrix 1 order = m x n (m rows and n columns)
Matrix 2 order = n x p (n rows and p columns)

Result matrix order = m x p (m rows and p columns)

Here, we are assuming input is given accurately.

Matrix Multiplication with Java Threads - Optimized Code (Parallel)


Monday, January 20, 2020

Java Thread States - Thread Life Cycle Flow - Multithreading Tutorial

1. Introduction


In this tutorial, We will see what is the life cycle of a Thread and what are the states involved in it. Typically, A thread can enter into any state by calling certain methods of thread. But, We can not see the thread state a particular time and but java builtin api has support to see the current status of running thread using getState() method.

In the previous article, we have seen the Thread concept of Thread Priorities.

Java Thread States - Thread Life Cycle Flow - Multithreading Tutorial

Friday, January 17, 2020

Java Thread characteristic Thread Priority - Multithreading

1. Introduction


In this article, We will understand one of two characteristics of Threads because those two are crucial for better analysis and debugging the issues. Here are the key factors of threads are Priority ad its State.

We have already explained how to create a thread using the Thread class and Runnable interface.

Remember, To run a java program one thread is required. When you are executing a program JVM will create a thread called Main thread that is the only thread created in normal and concurrent applications.

In java, Threads share all the resources of the application, including memory and open files. This is a powerful tool because they can share information in a fast and easy way but need to avoid race conditions using proper synchronization.

Java Thread characteristic Thread Priority  - Multithreading


Thursday, January 16, 2020

Creating Thread In Java - Multithreading Tutorial

1. Introduction


In this tutorial, We'll be learning how to create a thread in java. Before going to thread creation we should understand first the basic things about processors in our devices such as laptops and mobile smartphones.
Nowadays, we can use different applications at the same time. This can be working with Microsoft word document while listening to music or playing a game online. we can do all these things because we have an operating system that supports all of these.

Apart from different applications, we can do different works in one application. For instance, eclipse we can do write program and parallel we can run a search or building the application. Because our modern programming languages support to allow running multiple threads that run different tasks.

Coming to java, A Thread can be created in two ways as below.

A) Using Thread class
B) Using Runnable interface but we need to pass the object of this class to Thread class constructor.

Thread is a from java.lang package and Runnable is from java.util package.

Creating Thread In Java - Multithreading Tutorial


Saturday, January 4, 2020

How to Kill a Java Thread

1. Overview


In this tutorial, We will cover stopping a Thread in Java which is not that simple since the Thread.stop() method is deprecated. Because Thread.stop() method can lead to the monitored objects being corrupted. But, Still, many developers and applications are still using Thread.stop() method. Because they are not aware of its problems (monitored objects being corrupted.).

How to Kill a Java Thread Or How to stop a thread without using stop() method

let us see what are the other possible ways to stop the thread from its execution. This is a tricky topic for intermediate developers. Please read twice and practice the programs.