What is a Thread? How does it work?

18

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

  

Thread is a small program that works as a subsystem, being   a way for a process to self-divide into two or more tasks. It's the   term in English for Execution Thread or Thread . These tasks   can run simultaneously to run faster   than a program in a single block or almost together, but that   so fast that they seem to be working together at the same time.   time.

     

Complete article:    link   Canaltech content is protected under the Creative Commons license (CC   BY-NC-ND). You can play it as long as you enter COM   LINK to the original content and do not make commercial use of our   production.

However, I still can not understand it. How does thread work? If possible, could someone elucidate a practical example on Java on?

    
asked by anonymous 28.10.2015 / 23:20

2 answers

20

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

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

Using threads starts getting interesting when you want to run at least two things at once in a program to take advantage of multiple CPUs or to prevent the entire program from crashing when running a time-consuming operation.

The most common use case of threads in Java is to fulfill 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 handle each HTTP request in a different thread . This allows you to serve multiple users simultaneously and at the same time have some information isolation because the application server (such as Tomcat or JBoss) associates the data of each request with its thread , so this does with the same code being run by all users, but each with information isolated from one another.

See an illustration of the process ( source ):

    
29.10.2015 / 05:42
16

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);
        }
    }
}
    
29.10.2015 / 02:58