Multi Threading Using Lamda Expression | Join and IsAlive Methods In Multi Threading in Java

Multi Threading Using Lamda Expression | Join and IsAlive Methods In Multi Threading | Priority In Java Multi Threading

To Get a better understanding of this topic read the below two post before continuing this post.

What Is Multi Threading ? Why Do We Need Multi Threading In Java - Explained [THEORETICAL] 

How To Achieve Multi Threading in Java ? Extending Thread Class | Implementing Runnable Interface


Code:

public class ExampleCode 

{

public static void main(String[] args) 

{

Runnable hi=new Runnable() {

public void run()

{

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

{

System.out.println("Hi !");

try 

{

Thread.sleep(1000);

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

}

}

};

Runnable hello=new Runnable() {

public void run()

{

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

{

System.out.println("Hello !");

try 

{

Thread.sleep(1000);

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

}

}

};

Thread t1=new Thread(hi);

Thread t2=new Thread(hello);

t1.start();

t2.start();

}

}


If we take a look the above code it is similar to the example code of implementing Runnable interface code that we saw in the previous post.
But in this code we have modified the class that are declared in to Anonymous class. we can see that the classes are created inside the object creation of the Runnable. 

we can see that the Runnable Interface is a Functional Interface that means we can make use of the Lamda expression.

The below code has he changes to make it a lamda.

package firstcode;

public class ExampleCode 
{
public static void main(String[] args) 
{
Thread t1=new Thread( () -> {
for(int i=0;i<5;i++)
{
System.out.println("Hi !");
try 
{
Thread.sleep(1000);
} catch (Exception e) {System.out.println(e);}
}
});
Thread t2=new Thread(() -> {
for(int i=0;i<5;i++)
{
System.out.println("Hello !");
try 
{
Thread.sleep(1000);
} catch (Exception e) {System.out.println(e);}
}
});
t1.start();
t2.start();
}
}

Output :



Join Method in Multi Threading Programming :

Let's say we want to print bye after the hi and hello threads gets completed.
so if i add system out with bye as shown in the code below , the output is not like what we expected.

code :

public class ExampleCode 
{
public static void main(String[] args) 
{
Thread t1=new Thread( () -> {
for(int i=0;i<5;i++)
{
System.out.println("Hi !");
try 
{
Thread.sleep(1000);
} catch (Exception e) {System.out.println(e);}
}
});
Thread t2=new Thread(() -> {
for(int i=0;i<5;i++)
{
System.out.println("Hello !");
try 
{
Thread.sleep(1000);
} catch (Exception e) {System.out.println(e);}
}
});
t1.start();
t2.start();
System.out.println("Bye !");
}
}

 Output :



If you see the above output the bye is being printed before the hi and hello threads is completed.
The Reason is because,
We know that our main is also a thread.
we are creating two threads that are running but we need to note that our main thread is also been in running state so the bye is printed by main thread in parallel when hi and hello threads.

So what we need to do if we want to achieve what we want ?

Here comes the join() method.

code :

public class ExampleCode 
{
public static void main(String[] args) throws Exception
{
Thread t1=new Thread( () -> {
for(int i=0;i<5;i++)
{
System.out.println("Hi !");
try 
{
Thread.sleep(1000);
} catch (Exception e) {System.out.println(e);}
}
});
Thread t2=new Thread(() -> {
for(int i=0;i<5;i++)
{
System.out.println("Hello !");
try 
{
Thread.sleep(1000);
} catch (Exception e) {System.out.println(e);}
}
});
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Bye !");
}
}

Output :



The Join Method waits for the threads to complete its execution before going to the next step.
so now we got the bye after hi and hello threads are completed.

isAlive Method :

if we call this method it will return true if the thread is alive (i.e., in running state) else it will return false.

code:

public class ExampleCode 
{
public static void main(String[] args) throws Exception
{
Thread t1=new Thread( () -> {
for(int i=0;i<5;i++)
{
System.out.println("Hi !");
try 
{
Thread.sleep(1000);
} catch (Exception e) {System.out.println(e);}
}
});
Thread t2=new Thread(() -> {
for(int i=0;i<5;i++)
{
System.out.println("Hello !");
try 
{
Thread.sleep(1000);
} catch (Exception e) {System.out.println(e);}
}
});
t1.start();
t2.start();
System.out.println(t1.isAlive());
t1.join();
t2.join();
System.out.println(t1.isAlive());
System.out.println("Bye !");
}
}

Output:




we have checked isAlive() before thread t1 is completed(it returned true) and after t1 is completed(it returns false).


Continue Reading:

Priority in Java Multithreading | How to name a thread in java :

 

How To Achieve Multi Threading in Java ? Extending Thread Class | Implementing Runnable Interface

How To Achieve Multi Threading in Java ? Extending Thread Class | Implementing Runnable Interface

Before Reading this post if you have not seen the previous post on Multi Threading and why we need it ,first take a look at it with the below link and continue this post.

https://iamafutureprogrammer.blogspot.com/2021/11/what-is-multi-threading-why-do-we-need.html


Below is a simple java code that will print Hi and Hello 5 times by calling the method.

Code:

class SayHi

{

public void say()

{

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

{

System.out.println("Hi !");

try 

{

Thread.sleep(1000);

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

}

}

}


class SayHello

{

public void say()

{

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

{

System.out.println("Hello !");

try 

{

Thread.sleep(1000);

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

}

}

}


public class ExampleCode 

{

public static void main(String[] args) 

{

SayHi hi=new SayHi();

SayHello hello=new SayHello();

hi.say();

hello.say();

}

}


Output:



In the above java code we can see that after the hi.say() get executed the hello.say() starts its execution.
Note : the main method is by default a thread.

Sleep:

If we want to make our thread to suspend the execution for some time , then we can make use of Thread.sleep(1000) method.

we need to pass the milli seconds for which the execution needs to be suspended . e.g., 1000 means 1 seconds. So the it will print and wait 1 second for each.


Now our aim is to make the above program as multi threaded.
i.e., we are going to make both the hi.say() and hello.say() to execute in parallel.

Method 1 : Extending Thread Class 

To do that we can extend the thread class as follows.

package firstcode;

class SayHi extends Thread
{
public void run()
{
for(int i=0;i<5;i++)
{
System.out.println("Hi !");
try 
{
Thread.sleep(1000);
} catch (Exception e) {System.out.println(e);}
}
}
}

class SayHello extends Thread
{
public void run()
{
for(int i=0;i<5;i++)
{
System.out.println("Hello !");
try 
{
Thread.sleep(1000);
} catch (Exception e) {System.out.println(e);}
}
}
}

public class ExampleCode 
{
public static void main(String[] args) 
{
SayHi hi=new SayHi();
SayHello hello=new SayHello();
hi.start();
hello.start();
}
}

Output:


We need to extend the Thread Class to the classes for which we need to achieve threading.

we need to rename the method name as run() .
in spite of calling the method name we need to call a method called as start() .

the start method will invoke the run() method internally.

From the output we can see that the both the methods are executed parallely.

Note : the output we got above is not constant . see the below output for the same code when i ran again.

 You can see that they are executed in parallel but the order is different . 
This is because in Threading both the SayHi.start() and SayHello.start() will execute at the same time (may be  some millisecond difference) so the OS scheduler will decide what need to done first if both threads reaches the scheduler at the same time. the scheduler then randomly decides which one should be executed first. that's why we have a different output order.

Method 2 : Implementing Runnable Interface

Why we need to go for Runnable Interface when Thread Class is already there?

We know multiple inheritance is not supported in Java.
imagine we need a class A that needed to be extended to SayHi class above. at the same time we need to extend Thread class to.
so we need to do as below.

class SayHi extends A, Thread

But its not possible in java since it is a multiple inheritance.

So to over come this problem we make use of a interface called as Runnable.

Below is the same example we seen above now modified to use Runnable Interface.


Code:

package firstcode;

class SayHi implements Runnable
{
public void run()
{
for(int i=0;i<5;i++)
{
System.out.println("Hi !");
try 
{
Thread.sleep(1000);
} catch (Exception e) {System.out.println(e);}
}
}
}

class SayHello implements Runnable
{
public void run()
{
for(int i=0;i<5;i++)
{
System.out.println("Hello !");
try 
{
Thread.sleep(1000);
} catch (Exception e) {System.out.println(e);}
}
}
}

public class ExampleCode 
{
public static void main(String[] args) 
{
Runnable hi=new SayHi();
Runnable hello=new SayHello();
Thread t1=new Thread(hi);
Thread t2=new Thread(hello);
t1.start();
t2.start();
}
}

Output:



Runnable is a Functional Interface because it only has a single method called run().

Runnable has no start() method so we cannot call start() method directly . so we are making using of Thread class and taking the Runnable objects to it and then we are using the object of Thread class to call the start() method.

 

What Is Multi Threading ? Why Do We Need Multi Threading In Java - Explained [THEORETICAL]

 What Is Multi Threading ? Why Do We Need Multi Threading In Java - Explained  [THEORETICAL]

Before we get in to Threading we need to know about the below terms first for better understanding.

What is a Multi Tasking ?

Multi Tasking is the way of performing more than one task at the same time.

e.g., We May be Listening to music on Music Player in our laptop while we are Tying a document in MS Word.

Here two tasks are going on in parallel. And our system is also able to handle it . This is called as Multi Tasking.

What is a Process ?

A Process is nothing but a Single task.

e.g., when we are using MS Word , the whole running of MS Word is called as a Process.

What is a Thread ?

A Thread is a unit of a Process  or  called as sub process. 

A Single Process may have many number of threads .

The process will create threads when needed to do things in parallel.

e.g., when I open MS Word and Tying something , the MS Word not only is typing what I type , It also checks the spelling automatically.

Here, Whole MS Word is a Process.

Displaying What we type in the word is a Thread.

Spelling Check for the word we enter is a Thread.

What is Multi Threading?

A Process with 'n' number of threads is called as Multi Threading.

The example we saw in the Thread is a e.g., of Multi Threading.

Multi Threading

Why We need Multi Threading ?

The processors in current generation are becoming more powerful that they can handle huge operations easily.

we would have heard about dual core, quad core , octa core and hexa core processors .

e.g., octa core means a processor with 8 cores , means 8 individual processing units.

In order to make use of these huge processing units we are thinking to split the work to all the cores and and make execution time faster.

e.g., we are trying to find the square of 1lakh numbers. Lets imagine it took 8 seconds for the code to complete the execution.[ we have not implemented multi threading] - so the process will get processed by only one core even though we have 8 cores.

but if we execute the same code with multi threading in a 8 core machine it may take only 1 second. This is the power of multi threading. 



Do The Default Java Code is Treated as a Thread ?

Yes , The java program that we run are executed as thread by default. i.e., the main is the default Thread.


You can see when we get an exception , we would have seen "Exception in thread main" it says that our main method is a thread.


Real Time Mobile Apps where you would have seen the application of multi threading :

E.g., Amazon

we would have been in the main page of the amazon app. Its what the Main Process is running.


In the above screen shot of home page of the app when I clicked on a deal , it will create a new thread. it will happens every time when we make a request. 



Incase if the app does not use multithreading until the  response is got the app will be not responding.

Similar thing happens with servlet request handling to. 

The games that we play like PUBG , Counter Strike etc., also will use multithreading as there are multiple things that are happening with in the game. 


Continue Reading :

https://iamafutureprogrammer.blogspot.com/2021/11/how-to-achieve-multi-threading-in-java.html

Shutdown/Restart Windows With Simple Java Program

 Shutdown/Restart Windows With Simple Java Program


We can just make use of the Runtime class in java to execute the shutdown command using the simple java code.



We can shutdown from the command prompt itself.
To know the various ways to shutdown windows take a look at the below video.



Program : (Shut Down)

public class ShutDownMySystem 
{
public static void main(String[] args) 
{
Runtime runtime=Runtime.getRuntime();
try 
                {
System.out.println("shutting down ....");
runtime.exec("shutdown /s /t 0");
} 
                catch (Exception e) 
                {
System.out.println(e);
}
}
}





Program : (Restart)

public class RestartMySystem 
{
public static void main(String[] args) 
{
Runtime runtime=Runtime.getRuntime();
try 
                {
System.out.println("shutting down ....");
runtime.exec("shutdown /r");
} 
                catch (Exception e) 
                {
System.out.println(e);
}
}
}


Explanation:

/s - to shutdown
/t - to specify the time in seconds after to shutdown
/r - to restart


Output :

Take a look at the below video to see the the real time output.



Equals() and EqualsIgnoreCase() Method In Java Experimented And Explained (Java String Methods)

 Equals() and EqualsIgnoreCase() Method In Java Experimented And Explained (Java String Methods)


There are various predefined string functions(methods) in Java.

In this post we will explore two methods : equals() and equalsIgnoreCase().

equals() :

This method compares two string and returns true if both the strings are equal and returns false if both the strings are not equal.

Note : equals() is case sensitive i.e "A" and  "a" are not equal.

Syntax :  string1.equals(string2);

equalsIgnoreCase() :

This methos compares two string and returns true if both the strings are equal and returns false if both the strings are not equal.

The difference between equals() and equalsIgnoreCase() is that equalsIgnoreCase() ignores the case i.e "A"  and "a" are equals in equalsIgnoreCase() method.

Syntax : string1.equalsIgnoreCase(string2);


Java Example Code :


public class EqualsAndEqualsIgnoreCase 
{

public static void main(String[] args) 
{
String s1="Learn Programming";
String s2="learn programming";

//equals()

System.out.println(s1.equals(s2));  //returns false since equals will check case too i.e l and p mismatching

System.out.println(s1.equals("Learn Programming"));  //returns true since both are equal

System.out.println(s1.equals("Learn"));  //returns false 
//equalsIgnoreCase()

System.out.println(s1.equalsIgnoreCase(s2));  //returns true since it ignores case 

System.out.println(s1.equalsIgnoreCase("Learn Programming"));  //return true 

System.out.println(s1.equalsIgnoreCase("learn"));  //returns false
}

}



Output :



Contains Method In Java Explored And Experimented (String Functions In Java)

Contains Method In Java Explored And Experimented (String Functions In Java)


There are various inbuild string handling methods in java. 
In this post we will discuss about the .contains() method in java.


.contains() method will check whether a sequence of characters is in the given string.
This Method is Case sensitive.
 


Java Example Code :

public class ContainsMethod 
{
public static void main(String[] args) 
{
String s1="lets learn programming";
String s2="lets learn programmingg";
//1. contains() -> check whether string contains the given sequence of characters
System.out.println(s1.contains("Programming"));  // it return false because Programming and programming are not same i.e case sensitive
System.out.println(s1.contains("programming"));  // it return true because programming and programming are same
System.out.println(s1.contains("gram"));  // it return true because there is gram in programming
System.out.println(s1.contains("ts learn"));  // it return true because lets learn programming has ts learn in sequence


System.out.println(s1.contains(s2));  // it return false because there is extra g in s2 

System.out.println(s2.contains(s1));  // it return true because there is lets learn programming(s1) in lets learn programmingg(s2)

}
}


Output :




How To Open Applications With a Simple Java Code

How To Open Applications With a Simple Java Code


Explained YouTube video link : https://youtu.be/-RW2iC2UmNo

Below is a simple code which can open chrome browser .
you can replace the path with any applications path that you need to open.


public class OpenApp 
{
public static void main(String[] args) 
{
String s[]=new String[] {"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"};
try
{
Runtime runtime = Runtime.getRuntime();
runtime.exec(s);
}
catch(Exception e)
{
System.out.println(e);
}
}
}




C Code 40 _ To Write a C Program to Reverse each word in a given sentence

C Code 40 _ To Write a C Program to Reverse each word in a given sentence


Sample Input: 


abcd  efg  hij

Sample Output:


dcba  gfe  jih


Program:


#include<stdio.h>
#include<string.h>
int main()
{
char input[20];
int size,i,initial=0,j;
printf("\nEnter a Sentence : ");
gets(input);
size=strlen(input);
printf("\n\nSentence with reversed words : ");
for(i=0;i<=size;i++)
{ 
if(input[i]==' '||input[i]=='\0')
{
for(j=i-1;j>=initial;j--)
{
  printf("%c",input[j]);
}
printf(" ");
initial=i+1;
    }
}
return 0;
}



Output:










Thank You ...


* * * * * * * *  The above Program is contributed by AjayRam KV  * * * * * * * * *

C Code 39 _ To Find the sum of elements in each row of the given matrix

C Code 39 _ To Find the sum of elements in each row of the given matrix 

If a matrix is a 2x2 matrix then there are two rows .
so find the sum of elements in the two rows and display it.

Sample Input:

1 2 3
4 5 6

Sample Output:

sum of elements of row 1 is 6           //i.e. 1 + 2 + 3
sum of elements of row 2 is 15         //i.e. 4 + 5 + 6

Program:


#include<stdio.h>
int main()
{
int a[50][50];
int s[50];
int i,j,m,n,sum,k=0;
printf("\nEnter no of rows : ");
scanf("%d",&i);
printf("\nEnter no of columns : ");
scanf("%d",&j);
printf("\nEnter %d elements :  \n",i*j);
for(m=0;m<i;m++)
{
for(n=0;n<j;n++)
{
scanf("%d",&a[m][n]);
}
}
for(m=0;m<i;m++)
{
sum=0;
for(n=0;n<j;n++)
{
sum=sum+a[m][n];
}
s[k]=sum;
k=k+1;
}
printf("\n");
for(i=0;i<k;i++)
{
printf("\nSum of row %d is :  %d",i+1,s[i]);
}
return 0;
}


Output:











Thank You ...

C Code 38 _ To Find whether the given string has the characters arranged in alphabetical sequence order or not

C Code 38 _ To Find whether the given string has the characters arranged in alphabetical sequence order or not


Sample Input 1:

cdeg

Sample Output 1:

Characters are NOT in Sequence


Sample Input 2:

uvwxyz

Sample Output 2:

Characters are in sequence


Program:


#include<stdio.h>
int main()
{
int n,i,a,b,d=0;
char c[30];
printf("Enter a string of characters : ");
gets(c);
n=strlen(c);
for(i=0;i<n-1;i++)
{
a=c[i];
b=c[i+1];
if((a)!=(b-1))
{
d=1;
break;
}
}
if(d==0)
{
printf("\n\nThe Given Characters are in Sequence");
}
else
{
printf("\n\nThe Given characters are NOT in Sequence");
}
return 0;
}


Output:













Thank You ...


Popular Posts