Semáforos são variáveis protegidas, comumente utilizadas em programação multithread para controlar o acesso a recursos compartilhados. Analise o código a seguir em linguagem de programação Java.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
import java.util.concurrent.Semaphore; public class Compute implements Runnable { static int shared = 0; Semaphore semaphore; int id=0; public Compute(Semaphore semaphore) { this.semaphore = semaphore; this.id = ++Compute. shared; } public void run() { try { if (id%2 ==0){ semaphore.acquire(); for (int i = 0; i < 2;i++){ System.out.print(Integer.toString(id) + (++Compute.Shared)); Thread.sleep(10); } semaphore.release(); } else { semaphore.acquire(); for (int i = 0; i < 2; i++) { System.out.print(Integer.toString(id) + (--Compute.shared)); Thread.sleep(10); } semaphore.release(); } }catch(InterruptedException e) { e.printStackTrace();} } public static void main(String args[]) throws InterruptedException { Semaphore semaphore = new Semaphore(1); Thread dt1 = new Thread( new Compute(semaphore)); Thread dt2 = new Thread( new Compute(semaphore)); dt1.start(); dt2.start(); dt1.join(); dt2.join(); } } |
Ao executar esse programa em um terminal, em condições normais e sem a ocorrência de exceções, será escrito na saída padrão: