Buscar

Atividade de Sistemas Operacionais 2

Prévia do material em texto

CURSO: Análise e desenvolvimento de sistemas 
POLO DE APOIO PRESENCIAL: Higienópolis 
SEMESTRE: 2° semestre 
COMPONENTE CURRICULAR / TEMA: INTRODUÇÃO A SISTEMAS OPERACIONAIS 
NOME COMPLETO DO ALUNO: Maria Beatriz da Silva Souza 
TIA: 22516042 
NOME DO PROFESSOR: MARCELO TEIXEIRA DE AZEVEDO 
 
public class Main { 
 private static final int[] vetor = new int[100]; 
 private static final int numThreads = 2; 
 private static final int tamBloco = vetor.length / numThreads; 
 private static int[] somaParcial = new int[numThreads]; 
 
 public static void main(String[] args) throws InterruptedException { 
 // Preenche o vetor com valores aleatórios 
 preencherVetor(); 
 
 // Cria as threads 
 Thread[] threads = new Thread[numThreads]; 
 for (int i = 0; i < numThreads; i++) { 
 final int idThread = i; 
 threads[i] = new Thread(() -> { 
 // Soma os elementos do bloco correspondente 
 
 int inicio = idThread * tamBloco; 
 int fim = inicio + tamBloco; 
 for (int j = inicio; j < fim; j++) { 
 somaParcial[idThread] += vetor[j]; 
 } 
 }); 
 threads[i].start(); 
 } 
 
 // Espera todas as threads terminarem 
 for (int i = 0; i < numThreads; i++) { 
 threads[i].join(); 
 } 
 
 // Soma as somas parciais 
 int somaTotal = 0; 
 for (int i = 0; i < numThreads; i++) { 
 somaTotal += somaParcial[i]; 
 } 
 
 System.out.println("A soma dos elementos do vetor é " + somaTotal); 
 } 
 
 private static void preencherVetor() { 
 for (int i = 0; i < vetor.length; i++) { 
 vetor[i] = (int) (Math.random() * 100); 
 } 
 
 } 
}

Continue navegando