What is a Thread? How does it work?

Asked

Viewed 17,812 times

25

I was confused as to what a thread is and what it represents. I found the following definition for the same:

Thread is a small program that works as a subsystem, being a way for a process to split itself into two or more tasks. It is the term in English for Line or Thread Execution. These tasks multiple can be run simultaneously to run faster than a program in a single block or practically together, but which are so fast that they seem to be working together at the same time.

Full story: http://canaltech.com.br/o-que-e/o-que-e/o-que-e-thread/#ixzz3pu7fmDGh Canaltech content is protected under Creative Commons license (CC BY-NC-ND). You can play it as long as you enter credits LINK to the original content and make no commercial use of our producing.

However, I still can’t understand it. How does a thread? If possible, one could elucidate a practical example in Java about?

  • 5

    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.

2 answers

24


Think of a thread as a sequence of commands being executed in a program. If you have two threads, will have two sequences of commands running at the same time in the same program or process.

Note that running the same program twice is not creating more threads and create two processes of the same program. Threads run concurrently in the same process. Processes run concurrently in an operating system.

The use of threads starts to get interesting when you want to run at least two things at the same time in a program to take advantage of multiple Cpus or to prevent the entire program from getting stuck while performing a time consuming operation.

The most common use case of threads in Java is to meet requests in web applications. If you are somehow familiar with Servlets, Spring MVC, JSF, Struts or some other Java web framework, you should know that they all meet each HTTP request in one thread different. This allows to serve several users simultaneously and at the same time to have a certain isolation of the information, because the application server (such as Tomcat or Jboss) associates the data of each request with the respective thread, so this makes the same code run by all users, but each with information isolated from each other.

See an illustration of the process (source):

inserir a descrição da imagem aqui

18

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);
        }
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.