Java Tutorials
Java String toLowercase() and toUpperCase() Methods
1. tolowercase() method This Java string method converts every character of the particular string...
Any application can have multiple processes (instances). Each of this process can be assigned either as a single thread or multiple threads. We will see in this tutorial how to perform multiple tasks at the same time and also learn more about threads and synchronization between threads.
In this tutorial, we will learn:
A single thread is basically a lightweight and the smallest unit of processing. Java uses threads by using a "Thread Class".
There are two types of thread – user thread and daemon thread (daemon threads are used when we want to clean the application and are used in the background).
When an application first begins, user thread is created. Post that, we can create many user threads and daemon threads.
Single Thread Example:
package demotest;
public class GuruThread
{
public static void main(String[] args) {
System.out.println("Single Thread");
}
}Advantages of single thread:
MULTITHREADING in Java is a process of executing two or more threads simultaneously to maximum utilization of CPU. Multithreaded applications execute two or more threads run concurrently. Hence, it is also known as Concurrency in Java. Each thread runs parallel to each other. Mulitple threads don't allocate separate memory area, hence they save memory. Also, context switching between threads takes less time.
Example of Multi thread:
package demotest;
public class GuruThread1 implements Runnable
{
public static void main(String[] args) {
Thread guruThread1 = new Thread("Guru1");
Thread guruThread2 = new Thread("Guru2");
guruThread1.start();
guruThread2.start();
System.out.println("Thread names are following:");
System.out.println(guruThread1.getName());
System.out.println(guruThread2.getName());
}
@Override
public void run() {
}
}
Advantages of multithread:
The Lifecycle of a thread:
There are various stages of life cycle of thread as shown in above diagram:
Some of the commonly used methods for threads are:
| | |
|---|---|
| start() | This method starts the execution of the thread and JVM calls the run() method on the thread. |
| Sleep(int milliseconds) | This method makes the thread sleep hence the thread's execution will pause for milliseconds provided and after that, again the thread starts executing. This help in synchronization of the threads. |
| getName() | It returns the name of the thread. |
| setPriority(int newpriority) | It changes the priority of the thread. |
| yield () | It causes current thread on halt and other threads to execute. |
Example: In this example we are going to create a thread and explore built-in methods available for threads.
package demotest;
public class thread_example1 implements Runnable {
@Override
public void run() {
}
public static void main(String[] args) {
Thread guruthread1 = new Thread();
guruthread1.start();
try {
guruthread1.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
guruthread1.setPriority(1);
int gurupriority = guruthread1.getPriority();
System.out.println(gurupriority);
System.out.println("Thread Running");
}
}
Explanation of the code:
When you execute the above code, you get the following output:
Output:
5 is the Thread priority, and Thread Running is the text which is the output of our code.
In multithreading, there is the asynchronous behavior of the programs. If one thread is writing some data and another thread which is reading data at the same time, might create inconsistency in the application.
When there is a need to access the shared resources by two or more threads, then synchronization approach is utilized.
Java has provided synchronized methods to implement synchronized behavior.
In this approach, once the thread reaches inside the synchronized block, then no other thread can call that method on the same object. All threads have to wait till that thread finishes the synchronized block and comes out of that.
In this way, the synchronization helps in a multithreaded application. One thread has to wait till other thread finishes its execution only then the other threads are allowed for execution.
It can be written in the following form:
Synchronized(object)
{
//Block of statements to be synchronized
}In this example, we will take two threads and fetch the names of the thread.
Example1:
GuruThread1.java
package demotest;
public class GuruThread1 implements Runnable{
/**
* @param args
*/
public static void main(String[] args) {
Thread guruThread1 = new Thread("Guru1");
Thread guruThread2 = new Thread("Guru2");
guruThread1.start();
guruThread2.start();
System.out.println("Thread names are following:");
System.out.println(guruThread1.getName());
System.out.println(guruThread2.getName());
}
@Override
public void run() {
}
}
Explanation of the code:
When you execute the above code, you get the following output:
Output:
Thread names are being outputted here as
Example 2:
In this example, we will learn about overriding methods run() and start() method of a runnable interface and create two threads of that class and run them accordingly.
Also, we are taking two classes,
package demotest;
public class GuruThread2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
GuruThread3 threadguru1 = new GuruThread3("guru1");
threadguru1.start();
GuruThread3 threadguru2 = new GuruThread3("guru2");
threadguru2.start();
}
}
class GuruThread3 implements Runnable {
Thread guruthread;
private String guruname;
GuruThread3(String name) {
guruname = name;
}
@Override
public void run() {
System.out.println("Thread running" + guruname);
for (int i = 0; i < 4; i++) {
System.out.println(i);
System.out.println(guruname);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Thread has been interrupted");
}
}
}
public void start() {
System.out.println("Thread started");
if (guruthread == null) {
guruthread = new Thread(this, guruname);
guruthread.start();
}
}
}
Explanation of the code:
When you execute the above code you get the following output:
Output:
There are two threads hence, we get two times message "Thread started".
We get the names of the thread as we have outputted them.
It goes into for loop where we are printing the counter and thread name and counter starts with 0.
The loop executes three times and in between the thread is slept for 1000 milliseconds.
Hence, first, we get guru1 then guru2 then again guru2 because the thread sleeps here for 1000 milliseconds and then next guru1 and again guru1, thread sleeps for 1000 milliseconds, so we get guru2 and then guru1.
Summary:
In this tutorial, we saw multithreaded applications in Java and how to use single and multi threads.
1. tolowercase() method This Java string method converts every character of the particular string...
What is TypeScript? TypeScript is a superset of JavaScript. TypeScript is pure object-oriented...
You can use JavaScript code in two ways. You can either include the JavaScript code internally within...
Here are Java Collections Interview Questions for fresher as well as experienced candidates to get...
The String Class Java has three types of Replace methods: replace() replaceAll() replaceFirst() With...
In this JavaScript Unit Testing tutorial, we will learn: What is JavaScript? JavaScript is a...