Thread (em português: Linha ou Encadeamento de execução) é uma sequência de instruções programadas que podem ser gerenciadas independentemente pelo escalonador de processos do sistema operacional.
Thread é uma sequência de instruções programadas que podem ser gerenciadas independentemente pelo escalonador de processos do sistema operacional. Uma thread geralmente está contida dentro de um processo e um processo pode conter mais de uma thread.
Uma thread permite, por exemplo, que o usuário de um programa utilize uma funcionalidade do ambiente enquanto outras linhas de execução realizam outros cálculos e operações.
Os sistemas que suportam apenas uma única thread (em real execução) são chamados de monothread enquanto que os sistemas que suportam múltiplas threads são chamados de multithread.
Exemplos de threads em algumas linguagens de programação:
Java
import java.util.logging.Level;
import java.util.logging.Logger;
class Threaded extends Thread {
Synchronized1 base;
public Threaded( Synchronized1 bse ) {
this.base = bse;
}
}
public class Synchronized1 {
public Synchronized1() {
}
public void ini() {
new Threaded( this ) {
public void run() {
while( true ) {
synchronized( base ) {
System.out.print( "Este é A, agora vai mostrar B.\n" );
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(Synchronized1.class.getName()).log(Level.SEVERE, null, ex);
}
try {
base.notify();
base.wait();
} catch (InterruptedException ex) {
Logger.getLogger(Synchronized1.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}.start();
new Threaded( this ) {
public void run() {
while( true ) {
synchronized( base ) {
System.out.print( "Este é B, então foi já mostrado A.\n" );
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(Synchronized1.class.getName()).log(Level.SEVERE, null, ex);
}
try {
base.notify();
base.wait();
} catch (InterruptedException ex) {
Logger.getLogger(Synchronized1.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}.start();
}
public static void main(String[] args) {
new Synchronized1().ini();
}
}
C
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define THREADS_MAX 4
void *function(void *param)
{
int id = (int)param;
int i, loops = 10;
for(i = 0; i < loops; i++)
{
printf("thread %d: loop %d\n", id, i);
}
pthread_exit(NULL);
}
int main(void)
{
pthread_t threads[THREADS_MAX];
int i;
printf("pre-execution\n");
for (i = 0; i < THREADS_MAX; i++)
{
pthread_create(&threads[i], NULL, function, (void *)i);
}
printf("mid-execution\n");
for (i = 0; i < THREADS_MAX; i++)
{
pthread_join(threads[i], NULL);
}
printf("post-execution\n");
return EXIT_SUCCESS;
}
Ruby
count = 0
a = Thread.new { loop { count += 1 } }
sleep(0.1)
Thread.kill(a)
puts count #=> 93947