Check thread asleep from another thread

1

I have a problem with the java threads. The issue is that I have a thread that runs every 10 minutes, but it takes a few times to execute X times, and other times And, so to speak. They can be 5 seconds, or 7 or 10, you do not know. The issue is that I need the other thread to run after the first one runs. I had thought about doing a if(hilo.isInterrupted()) from thread 2, but it will not let me. Any idea how to do it? Clarify that it is a web application and both threads start from superinit from the initial controller of my project. I had also thought about one thread calling another, but I do not really know how to do thread 1 first, and then thread 2.

package Hilos;

import BD.*;
import Clases.*;
import Hilos.*;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class HiloPartidos extends Thread {

SQLBD baseDatos = new SQLBD();
String idPartidoBD;
String idPartido;
String round;
String local;
String visitante;
String idLiga;
String equipo1;
String equipo2;
String localAbbr;
String visitanteAbbr;
String nombreCompeticion;
String fecha;
String resultado;
String ganador;
String estado;
String vFecha;
Thread hiloApuestas = new HiloPartidos();

@Override
public void run() {

    while (!this.isInterrupted()) {
        try {
            //URL url = new URL("http://apiclient.resultados-futbol.com/scripts/api/api.php?key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxtz=Europe/Madrid&format=xml&req=matchs&league=1&round=38&order=twin&twolegged=1&year=2017");
            //URLConnection urlConnection = url.openConnection();
            //InputStream in = new BufferedInputStream(urlConnection.getInputStream());
            File xmlFile = new File( "/archivo.xml" );
            DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            //Document doc = (Document) db.parse(in);
            Document doc = (Document) db.parse(xmlFile);
            NodeList nList = doc.getElementsByTagName("match");
            for (int temp = 0; temp < nList.getLength(); temp++) {

                Node nNode = nList.item(temp);

                if (nNode.getNodeType() == Node.ELEMENT_NODE) {

                    Element eElement = (Element) nNode;
                    idPartido = eElement.getElementsByTagName("id").item(0).getTextContent();
                    //idPartido=idPartido.substring(2);
                    round = eElement.getElementsByTagName("round").item(0).getTextContent();
                    //round=round.substring(2);
                    local = eElement.getElementsByTagName("local").item(0).getTextContent();
                    //local = local.substring(2);
                    visitante = eElement.getElementsByTagName("visitor").item(0).getTextContent();
                    //visitante = visitante.substring(2);
                    idLiga = eElement.getElementsByTagName("league_id").item(0).getTextContent();
                    //idLiga = idLiga.substring(2);
                    equipo1 = eElement.getElementsByTagName("team1").item(0).getTextContent();
                    //equipo1 = equipo2.substring(2);
                    equipo2 = eElement.getElementsByTagName("team2").item(0).getTextContent();
                    //equipo2 = equipo2.substring(2);
                    localAbbr = eElement.getElementsByTagName("local_abbr").item(0).getTextContent();
                    //localAbbr = localAbbr.substring(2);
                    visitanteAbbr = eElement.getElementsByTagName("visitor_abbr").item(0).getTextContent();
                    //visitanteAbbr = visitanteAbbr.substring(2);
                    nombreCompeticion = eElement.getElementsByTagName("competition_name").item(0).getTextContent();
                    //nombreCompeticion = nombreCompeticion.substring(2);
                    fecha = eElement.getElementsByTagName("schedule").item(0).getTextContent();
                    //fecha = fecha.substring(2);
                    resultado = eElement.getElementsByTagName("result").item(0).getTextContent();
                    //resultado = resultado.substring(2);
                    ganador = eElement.getElementsByTagName("winner").item(0).getTextContent();
                    //ganador = ganador.substring(2);

                    idPartidoBD = baseDatos.consultarPartidosFutbol(idPartido);

                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    System.out.println(fecha);
                    Date date = sdf.parse(fecha);
                    long fechaApi = date.getTime();

                    java.util.Date vfecha = new Date();
                    long fechaActual = vfecha.getTime();

                    if(fechaActual <= fechaApi){
                        estado="pendiente";
                    }else{
                        estado = "empezado";
                    }



                    // use SimpleDateFormat to define how to PARSE the INPUT
                    if(idPartidoBD != ""){
                        baseDatos.insertPartidoFutbol(idPartido, round, local, visitante, idLiga, equipo1, equipo2, localAbbr, visitanteAbbr, nombreCompeticion, fecha, resultado, ganador, estado);
                    }else{
                        baseDatos.updatePartidoFutbol(idPartido, round, local, visitante, idLiga, equipo1, equipo2, localAbbr, visitanteAbbr, nombreCompeticion, fecha, resultado, ganador, estado, idPartidoBD);
                    }
                }
            }

            hiloApuestas.start();
            Thread.sleep(600000);
        } catch (Exception e) {
        e.printStackTrace();
        }
    }
}
}







package Hilos;

import BD.*;
import Clases.*;
import Hilos.*;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;


public class HiloApuestas extends Thread {

SQLBD baseDatos = new SQLBD();


@Override
public void run() {

    while (!this.isInterrupted()) {
        try {
            ResultSet rset = baseDatos.consultarEstadoPartidos();

            Thread.sleep(60000);
        } catch (Exception e) {
        e.printStackTrace();
        }
    }
}

}

    
asked by urrutias 30.05.2017 в 12:44
source

2 answers

1

A simple option (if you know that the first thread is running) is to join your current thread to that (method join so that your current thread stays locked until the first thread ends.

A somewhat better solution in my opinion is that you use some type of wake-up callback ( notify to your second thread from the first as soon as it finishes. The downside is that this would mean sleeping ( wait ) your second thread first, and maybe it's not what you want.

The best solution in my opinion is that you had a Executor of a single thread for each of the tasks. The Executor of the second task can be stopped and when finishing the first thread it could activate the Executor of the second one.

A variation of the last solution would be to make an Executor of a single thread and put both tasks in order. This guarantees that as soon as the first one is finished, the second one will be executed. I recommend looking at the Java Executor as they allow you to do many complicated concurrency tasks with ease.

    
answered by 30.05.2017 в 15:57
0

The best thread practice for these problems is to use the wait () and notiify () methods to block and release the threads at the time that is necessary. You would have to put in wait the second thread and when the first one ends, invoke notify as the last action to "warn" thread 2 that it finished its execution and that it should start working. All this is implemented using an object with a variable flag that informs the state of thread 1 (idle, working, end of execution) and that reads thread 2 to know whether to work or wait ....

    
answered by 30.05.2017 в 15:50