Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Threads run in series? (Second thread does not run until first thread stops)

I am starting two thread one after the other. The first thread is reading in a loop from input and the other one check some condition in a loop to sent an interrupt to the other.

The problem is that any thread of the two I start first it doesnt let the other stop. If i start reading in never runs the other thread until it finishes and if I start the other thread is checking the condition in the loop and it wont move forward in code until the condition is true and gets out of the loop. What is the correct way to do it? Sample code below:

Thread 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;
      }
   }
}

Thread 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);
      }
   }
}
like image 809
user847988 Avatar asked Mar 10 '26 08:03

user847988


1 Answers

This sounds like you are not starting the threads in a correct manner.

Use the start() method to start threads, not the run() method (which doesn't actually start a thread).

new InterruptionThread().start();
new ReadingThread().start();
like image 175
Dan D. Avatar answered Mar 12 '26 22:03

Dan D.