简单线程是串联运行的吗?(第二个线程在第一个线程停止之前不会运行)

use*_*988 3 java multithreading

我一个接一个地开始两个线程.第一个线程是从输入读取循环,另一个是在循环中检查某些条件以向另一个发送中断.

问题是我先启动的两个线程中的任何线程都不会让另一个线程停止.如果我开始读取从不运行另一个线程,直到它完成,如果我启动另一个线程正在检查循环中的条件,它不会在代码中向前移动,直到条件为真并退出循环.这样做的正确方法是什么?示例代码如下:

线程1)

public class InterruptionThread extends Thread {
   public void run() {

      while (condition not true) {
         try {
            sleep(1000);
         } catch (InterruptedException e) {
            e.printStackTrace();
         }

      }
      if (condition true) {
         do some work
         return;
      }
   }
}
Run Code Online (Sandbox Code Playgroud)

线程2)

public class ReadingThread extends Thread{

   public void run() {
      int input;
      while (true) {
         try {
            input = stdInput.read();
         } catch (IOException e) {
            e.printStackTrace();
            return;
         }
         System.out.print((char) input);
      }
   }
}
Run Code Online (Sandbox Code Playgroud)

Dan*_* D. 5

这听起来好像你没有以正确的方式启动线程.

使用start()方法启动线程,没有run()方法(实际上并没有启动一个线程).

new InterruptionThread().start();
new ReadingThread().start();
Run Code Online (Sandbox Code Playgroud)