Threads
in Java (the class java.lang.Thread
) are abstractions of threads of the operating system.
In the operating system
A (or a) thread is a sequence of commands being executed in a program or process. If you have two threads, will have two sequences of commands running in parallel in the same process.
As threads of a process share the call execution context, that changing into kids means that they all have the same view of the memory occupied by the process. With this, the variables and functions of a thread can also be accessed by other threads.
The memory of a process is not shared by other processes, so it is more difficult to get two processes to talk. With threads this becomes simpler. Processes are only able to share information indirectly (through sockets or Pipes, for example).
Why modern operating systems allow programming in threads besides lawsuits? Because in addition to making multitasking simpler, it is more efficient (because the scheduler is constantly changing execution context and this exchange has a cost, which is less than one thread to another than from one process to another, since the memory context is the same).
One last thing about threads: a process normally starts running a single thread, which is able to subdivide into a second thread, and so on to create new threads (one thread arising from the division of an existing).
In Java
One Thread
in Java (the class java.lang.Thread
) allows your Java application to run a sequence of instructions on a thread of the virtual machine, which in practice is executed by a thread the host operating system or kernel thread (recalling that the Java virtual machine runs on top of a host operating system).
These sequence instructions are encapsulated within a method run()
which is passed to the builder of Thread
(not the method directly, but an object Runnable
, that is, that implements the interface Runnable
and therefore implements the method run()
). Or, alternatively, since the class itself Thread
already implements Runnable
, you can choose to simply implement this method in the class object itself Thread
.
But only give a method run()
à Thread
does not cause it to rotate parallel to others threads. It is necessary to start it by calling the method Thread.start()
.
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 decreased because the second thread runs faster than the first (your sleep intervals are shorter).
Also note that if you uncomment the println()
commented on the method dormir()
, will see that the same code snippet (the method dormir()
) is being called by two threads different.
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);
}
}
}
One of the results of https://www.bing.com/search?q=o+que+é+um+thread+ has a good explanation: http://www.macoratti.net/10/09/c_thd1.htm. He talks about C#, but the concepts are the same for Java.
– carlosfigueira