Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
237 views
in Technique[技术] by (71.8m points)

java - 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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...