Basic Threading Concepts

In this exercise, you will learn the basics of **threads** in Java. Threads allow multiple tasks to run concurrently, improving application performance and responsiveness. You will see how to create, manage, and run threads in Java to perform parallel operations, optimizing the use of system resources.

Topic

Threads and Concurrency

Java Exercise

In this exercise, you will create a Java program that demonstrates thread creation and execution using the Thread class. First, you will create a class that extends Thread and implements its run() method. Then, in the main method, you will create objects of this class and start them to execute tasks in parallel. Finally, you will learn how to manage concurrent thread execution to improve your application's performance.

Instructions:

  1. Create a class that extends Thread and implements the run() method.
  2. In the run() method, define the behavior of the thread that will execute concurrently.
  3. In the main method, create several objects of the class you created and call start() to start the threads.
  4. Observe how the threads execute in parallel, printing a message to the console.

This exercise will help you understand the basic concepts of **concurrency** in Java and how threads can be used to execute tasks in parallel, optimizing the performance of your application.


// Class that extends Thread
class MyThread extends Thread {
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getId() + " - Thread is running");
    }
}

public class Main {
    public static void main(String[] args) {
        // Create objects of the MyThread class
        MyThread thread1 = new MyThread();
        MyThread thread2 = new MyThread();
        MyThread thread3 = new MyThread();

        // Start the threads
        thread1.start();
        thread2.start();
        thread3.start();
    }
}

 Output:

11 - Thread running
12 - Thread running
13 - Thread running

This program demonstrates how threads are created and managed in Java. The MyThread class extends Thread and overloads the run() method to define thread behavior. When you run the program, three threads are created, started with the start() method, and you can see how they run concurrently, each printing a message to the console with its thread ID.


 Share this JAVA exercise