We know that a class that extends from Thread
has a method run()
which is an independent thread, but how can I have several threads in a single class?
For example, if I have a class Jugador
and it has 2 methods (run, shoot), how can I make those 2 methods independent threads in 1 same class. Or you would have to create 2 classes, one for running and one for firing, because you can only have one method run()
.
Main
package hilos;
public class Hilos {
public static void main(String[] args) {
acciones accion1 = new acciones();
accion1.start();
}
}
Class with Threads
package hilos;
public class acciones extends Thread {
@Override
public void run()
{
// Código para correr
}
// Código para correr para nadar ????????????? como seria ??
}
The first thing to clarify is that the
run
class methodThread
is not a thread itself. The classThread
allows us to create independent threads on our own to execute a certain code that is what we include inside its methodrun
. How does this work (roughly and without getting too technical? Well, when we create an object of typeThread
and execute its methodstart
, we are telling the Java virtual machine to create a new thread and execute the method code within itrun
.Having the above clear, and to achieve what you ask for, the following occurs to me:
Here what we did was create an object of type
Acciones
and execute each of its methods in aThread
separate.Note : In case you are not familiar with functional programming in Java, this code:
It is equivalent to
IMPORTANT: If the methods of a class are executed in different threads and these methods use shared resources of the class itself, you must use mutual exclusion techniques such as synchronization. This also applies to those methods that share any type of resources, whether these methods are in the same class or not. Multiprogramming or concurrent programming is not a trivial topic and I recommend that you study it in depth before applying it to real projects.