Threads
in Java (the java.lang.Thread
class) are operating-system abstractions of threads .
In the operating system
A thread is a sequence of commands being executed in a program or process. If you have two threads , you will have two command sequences running in parallel in the same process.
The threads in a process share the execution context , which in turn means that they all have the same view of the memory occupied by the process. Thus, the variables and functions of a thread can also be accessed by the other threads .
The memory of a process is not shared by other processes, so it is more difficult to make two processes talk. With threads this gets simpler. Processes are only able to share information in an indirect way (via sockets or pipes , for example).
Why do modern operating systems allow programming in threads as well as processes? Because it makes multi-task scheduling simpler, it is more efficient (because the scheduler is changing its execution context all the time, and this change has a cost that is less than one thread for another from one process to another, since the memory context is the same.)
One last thing about threads : A process normally starts by running a single thread , which is able to subdivide into a second thread and so on to create new threads (a thread from the split of an existing one).
In Java
A
Thread
in Java (the
java.lang.Thread
class) allows your Java application to run a sequence of instructions in a thread of the virtual machine, which is actually executed by a thread of the host operating system or kernel thread (remembering that the Java virtual machine runs on top of a host operating system).
These instruction sequences are encapsulated within a run()
method that is passed to the Thread
constructor (not the method directly, but a Runnable
object, that is, it implements the Runnable
interface and which therefore implements the run()
method). Or, alternatively, since the Thread
class itself already implements Runnable
, you can choose to simply implement this method in the Thread
object itself.
However, only giving a method run()
to Thread
does not make it run in parallel to other threads . You must start it by calling the Thread.start()
method.
Example
Here two threads compete with each other to change the value of a variable. One increments the value of the variable and the other decreases the value. Eventually the value will be decremented because the second thread runs faster than the first (its sleep intervals are shorter).
Also note that if you uncomment the% com_commented_comment of the println()
method, you will see that the same code snippet (the dormir()
method) is being called by two different threads / p>
public class TesteComThreads {
public int variavelCompartilhada = 0;
public static void main(String [] args) {
new TesteComThreads().executar();
}
public void executar() {
Thread segundoThread = new ThreadQueDecrementaValorDaVariavel(this);
segundoThread.start();
while(true) {
variavelCompartilhada++;
System.out.println("Variável vale: " + variavelCompartilhada);
dormir(1500);
}
}
public void dormir(int milissegundos) {
try {
// System.out.println(Thread.currentThread().getName() + " irá dormir por " + milissegundos + " milissegundos.");
Thread.sleep(milissegundos);
} catch (InterruptedException e) {
// Não precisa fazer nada
}
}
}
class ThreadQueDecrementaValorDaVariavel extends Thread {
private TesteComThreads teste;
public ThreadQueDecrementaValorDaVariavel(TesteComThreads teste) {
this.teste = teste;
}
@Override
public void run() {
while(true) {
teste.variavelCompartilhada--;
System.out.println("Variável vale: " + teste.variavelCompartilhada);
teste.dormir(1000);
}
}
}