Sobes.tech
Junior — Middle

How to implement simultaneous execution of two threads in a program?

sobes.tech AI

Answer from AI

To run two threads simultaneously in Java, you can create two Thread objects or implement the Runnable interface and start them concurrently.

Example using Thread:

public class MyThread extends Thread {
    private String name;

    public MyThread(String name) {
        this.name = name;
    }

    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println(name + " - counter: " + i);
            try {
                Thread.sleep(500); // pause for 500 ms
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

public class Main {
    public static void main(String[] args) {
        Thread t1 = new MyThread("Thread 1");
        Thread t2 = new MyThread("Thread 2");

        t1.start(); // start first thread
        t2.start(); // start second thread
    }
}

When run, both threads will execute in parallel, printing their messages to the console.

How to implement simultaneous execution of two… - sobes.tech