Threading of threads in Java

1

I'm testing threads in Java and I've stayed in a part where I do not know how to continue. The problem is this:

I have 3 threads running and I would like to know how I can stop the second thread only if the first thread is suspended. The part of suspending the first thread works for me (when it reaches 15 the first thread stops), but I can not make the second one stop. I have seen by some sites that the isAlive method is done, but I do not know how to apply it.

I enclose what I have of the code.

public class Hilos extends Thread {

public Hilos(String nombre) {
    super(nombre);
}

@Override
public void run() {
    for (int i = 1; i < 26; i++) {
        System.out.println("" + getName() + " paso " + i);

        if ((i == 15) && (getName().equals("Hilo 1"))) {
            System.out.println("" + getName() + " está suspendido.");
            suspend();

        }

        System.out.println("Acaba " + getName());
    }

}

public static void main(String[] args) {
    Hilos h1 = new Hilos("Hilo 1");
    Hilos h2 = new Hilos("Hilo 2");
    Hilos h3 = new Hilos("Hilo 3");

    h1.start();
    h2.start();
    h3.start();
}
}
    
asked by druix 30.05.2016 в 20:21
source

2 answers

2

Perhaps the most logical thing would be to pause Hilo2 from Hilo1 before doing the suspend (), but not always the most logical solution is the most functional.

Go over this code, in which a coordinator is used for the understanding between the two threads:

final Thread subject1 = new Thread(new Runnable() {

  public void run() {
    while (!Thread.interrupted()) {
      Thread.yield();
    }
    System.out.println("subject 1 stopped!");
  }
});

final Thread subject2 = new Thread(new Runnable() {

  public void run() {
    while (!Thread.interrupted()) {
      Thread.yield();
    }
    System.out.println("subject 2 stopped!");
  }
});

final Thread coordinator = new Thread(new Runnable() {

  public void run() {
    try {
      Thread.sleep(500);
    } catch (InterruptedException ex) { }
    System.out.println("coordinator stopping!");
    subject1.interrupt();
    subject2.interrupt();
  }
});

subject1.start();
subject2.start();
coordinator.start();
    
answered by 31.05.2016 в 08:30
0

The methods stop () , suspend () and resume () are marked @Deprecated and do not It is advisable to continue using them.

It is recommended to simply leave the run () method of the thread for example with a return, so the thread ends naturally.

    
answered by 06.01.2017 в 05:40