Salitha10
Salitha10

Reputation: 9

How to print sentences in both threads?

class X1 extends Thread {
 public void run() {
    System.out.println("I am X1");
  }
}

class Y2{
  public void run() {
    while (true)
    System.out.println("I am Y2");
  }
}

class Test {
  public static void main(String[] s) {
    X1 a = new X1();
    Y2 b = new Y2();
    
    b.run();
    a.start();
  }
}

This code is supposed to display both “I am X1” and an infinite number of “I am Y2”. But it only prints “I am Y2”. How to fix it?

Upvotes: 1

Views: 55

Answers (1)

Eran
Eran

Reputation: 393811

b.run() doesn't start a new thread. It executes the run() method on the main thread. And since that method contains an infinite loop, it never terminates, so a.start() is never executed, and the second thread is never started.

You can either reverse the order of the calls:

a.start(); // first start the second thread
b.run(); // then run the infinite loop on the main thread

Or run b's run() method on a separate thread:

new Thread(() -> b.run()).start();
a.start();

Or if you change Y2 to implement Runnable:

new Thread(b).start();
a.start();

Upvotes: 3

Related Questions