Java programming in thread main

Java Threads

Threads allows a program to operate more efficiently by doing multiple things at the same time.

Threads can be used to perform complicated tasks in the background without interrupting the main program.

Creating a Thread

There are two ways to create a thread.

It can be created by extending the Thread class and overriding its run() method:

Extend Syntax

public class Main extends Thread < public void run() < System.out.println("This code is running in a thread"); > >

Another way to create a thread is to implement the Runnable interface:

Implement Syntax

public class Main implements Runnable < public void run() < System.out.println("This code is running in a thread"); >>

Running Threads

If the class extends the Thread class, the thread can be run by creating an instance of the class and call its start() method:

Extend Example

public class Main extends Thread < public static void main(String[] args) < Main thread = new Main(); thread.start(); System.out.println("This code is outside of the thread"); >public void run() < System.out.println("This code is running in a thread"); >>

If the class implements the Runnable interface, the thread can be run by passing an instance of the class to a Thread object's constructor and then calling the thread's start() method:

Implement Example

public class Main implements Runnable < public static void main(String[] args) < Main obj = new Main(); Thread thread = new Thread(obj); thread.start(); System.out.println("This code is outside of the thread"); >public void run() < System.out.println("This code is running in a thread"); >>

Differences between "extending" and "implementing" Threads

The major difference is that when a class extends the Thread class, you cannot extend any other class, but by implementing the Runnable interface, it is possible to extend from another class as well, like: class MyClass extends OtherClass implements Runnable .

Concurrency Problems

Because threads run at the same time as other parts of the program, there is no way to know in which order the code will run. When the threads and main program are reading and writing the same variables, the values are unpredictable. The problems that result from this are called concurrency problems.

Example

A code example where the value of the variable amount is unpredictable:

public class Main extends Thread < public static int amount = 0; public static void main(String[] args) < Main thread = new Main(); thread.start(); System.out.println(amount); amount++; System.out.println(amount); > public void run() < amount++; > >

To avoid concurrency problems, it is best to share as few attributes between threads as possible. If attributes need to be shared, one possible solution is to use the isAlive() method of the thread to check whether the thread has finished running before using any attributes that the thread can change.

Example

Use isAlive() to prevent concurrency problems:

public class Main extends Thread < public static int amount = 0; public static void main(String[] args) < Main thread = new Main(); thread.start(); // Wait for the thread to finish while(thread.isAlive()) < System.out.println("Waiting. "); > // Update amount and print its value System.out.println("Main: " + amount); amount++; System.out.println("Main: " + amount); > public void run() < amount++; > >

Источник

Читайте также:  Пустые сервера awp css v34

Java programming in thread main

  • Introduction to Java
  • The complete History of Java Programming Language
  • C++ vs Java vs Python
  • How to Download and Install Java for 64 bit machine?
  • Setting up the environment in Java
  • How to Download and Install Eclipse on Windows?
  • JDK in Java
  • How JVM Works – JVM Architecture?
  • Differences between JDK, JRE and JVM
  • Just In Time Compiler
  • Difference between JIT and JVM in Java
  • Difference between Byte Code and Machine Code
  • How is Java platform independent?
  • Decision Making in Java (if, if-else, switch, break, continue, jump)
  • Java if statement with Examples
  • Java if-else
  • Java if-else-if ladder with Examples
  • Loops in Java
  • For Loop in Java
  • Java while loop with Examples
  • Java do-while loop with Examples
  • For-each loop in Java
  • Continue Statement in Java
  • Break statement in Java
  • Usage of Break keyword in Java
  • return keyword in Java
  • Object Oriented Programming (OOPs) Concept in Java
  • Why Java is not a purely Object-Oriented Language?
  • Classes and Objects in Java
  • Naming Conventions in Java
  • Java Methods
  • Access Modifiers in Java
  • Java Constructors
  • Four Main Object Oriented Programming Concepts of Java
  • Inheritance in Java
  • Abstraction in Java
  • Encapsulation in Java
  • Polymorphism in Java
  • Interfaces in Java
  • ‘this’ reference in Java

Источник

What is Thread in Java | Main Thread, Use

Scientech Easy

A thread in Java simply represents a single independent path of execution of a group of statements. It is the flow of execution, from beginning to end, of a task.

When we write a group of statements in a program, these statements are executed by JVM one by one. This execution process is called thread in Java.

There is always at least one thread running internally in every program and this thread is used by JVM to execute statements in the program.

When a program contains a single flow of control, it is called single-threaded program. In a single thread program, there is a beginning, a body, and an end, and execute commands sequentially. Look at the below figure.

Single threaded program in Java

We can also create more than one execution thread in a program that can be used to perform multiple tasks simultaneously.

When we create more than one thread in a program, each thread has its own path of execution and all the threads share the same memory address space, data, and code in a program.

What is Process in Java?

Thread in Java is the smallest unit of executable code in a program. It helps to divide a program into multiple parts to speed up the process.

A process is a program that executes as a single thread. In other words, when an executable program is loaded into memory, it is called process.

Points to be Noted:

1. Every individual process has its own separate memory address space and can execute a different program.

2. Each process can have more than one thread.

3. Each process communicates through the operating system, files, and network.

Читайте также:  Php melody all rights reserved

When we will create a new thread in a program, it shares the same memory address space with other threads in a program whereas every individual process has its own separate memory address space.

Therefore, creating a thread takes fewer resources than creating a new process. Look at the below figure to understand better.

Thread in Java

As you can see in the above figure, the thread is executed inside a process and one process can have also multiple threads. There can be multiple processes inside the operating system.

Multiple Threads are independent of each other. At a time, only one thread is executed. If an exception occurs in one thread, it doesn’t affect other threads.

Why Java threads are lightweight process?

Java Threads are also known as lightweight threads or light-weight processes. It means that they can be executed in the same memory space because all the threads in the main application program share the same address space in the memory so that they can easily communicate among themselves. Thus, they also take less space in memory and less processor time.

Main Thread in Java

Every Java program has always at least one thread, even if you do not create any thread. This thread is called main thread.

The main thread is also called parent thread and the rest of threads that are generated from it are called child threads of the program.

Main thread is the last thread to be executed in a program. When main thread finishes the execution, the program terminates immediately. Whenever Java program starts, main thread is created automatically.

This main thread is available in all programs. We can control the execution of the main thread by creating a Thread object and then using methods of Thread class.

To do so, we will have to create a Thread object by calling currentThread() method of class Thread. A Thread object can be created as follows:

Thread obj = Thread.currentThread();

Since currentThread() method of class Thread is a public static method, therefore, we can call it using class name.

The currentThread() method returns a reference of current thread on which it is called. “obj” is a reference variable that is assigned to store the return value of currentThread() method.

Let’s create a Java program to find the thread used by JVM to execute statements and display the name of main thread.

Program code:

Output: Current thread is Thread[main,5,main] Name of current thread is main

Explanation:

1. In this program, currentThread() is a static method in a class Thread. Therefore, we called it as Thread.currentThread(). This method returns the reference of main thread because this is called inside the main thread. The reference of main thread will be stored in a variable obj of type Thread.

2. When line 8 will be executed by JVM, it will display an output “Thread[main,5,main]” on screen. In the square bracket, the first value, main represents the name of thread; second value 5 represents the priority of main thread.

Every thread will have a priority number associated with it that can be range from 1 to 10. 1 is the minimum priority and 10 is the maximum priority of a thread.

Читайте также:  Php как скрыть checkbox

The third value main represents the name of group to which main thread belongs.

3. getName() method of Thread class returns the name of thread that is referred by object obj.

Let’s make a Java program in which we will control main thread and also change name of main thread.

Program code:

public class MainThreadDemo < public static void main(String[] args) < // Create a Thread object by calling currentThread() method of class Thread. Thread obj = Thread.currentThread(); System.out.println("Current thread is " +obj); System.out.println("Name of current thread is " +obj.getName()); obj.setName("New Thread"); // Changing name of main thread. System.out.println("Name of current thread after changing name is " +obj); System.out.println("Main thread existing"); >>
Output: Current thread is Thread[main,5,main] Name of current thread is main Name of current thread after changing name is Thread[New Thread,5,main] Main thread existing

In the preceding program, the name of main thread is changed by calling setName() method of Thread class and a new name of main thread is displayed. The new name of main thread is New Thread.

Use of Thread in Java

Threads can be used for multiple purposes. Some advantages of using threads are as follows:

1. We mainly used threads in server-side programs where we need to handle multiple clients on network or internet simultaneously.

2. Another important use of threads is in creating games and animations. For example, threads can be used to show picture in motion. In many games, threads help to perform more than one task simultaneously.

For example, in a fighter game, a fighter plane may be from left to right. A machine gun in fighter plane continuously shoots enemy by releasing bullets.

Here, two tasks are happening simultaneously. One thread is moving the fighter plane while another thread releasing bullets simultaneously.

3. Generally, threads can be used to perform more than one task simultaneously.

A program running on a single thread can cause problems when we want to perform two or more tasks simultaneously.

For example, when you play online cricket game, you sometimes see such a situation where the game does not show the updated score but still displays graphics properly.

Here, displaying graphics of game and updating scores are two different jobs that are to be handled at the same time. Therefore, it is important that the game programming must be able to handle these multiple tasks to make game fast.

To overcome these problems, Java supports multithreaded programming that enables a single program to perform multiple tasks simultaneously.

In multithreaded programming, each thread is assigned to perform a single task and executes independently. Multiple threads in a program share the same memory address space among themselves.

Hope that this tutorial has covered all the important points related to what is thread in java, main thread, and use of thread. I hope that you will have understood the basics of thread.

In the next tutorial, we will know multithreading in Java in more detail.
Thanks for reading.
Next ⇒ Multithreading in Java ⇐ Prev Next ⇒

Источник

Оцените статью