/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import java.util.concurrent.Semaphore;
/**
*
* @author ZTI
*/
/********************************
* Zadanie polega na zsynchronizowaniu wątków P1, P2, P3 oraz P4
* tak aby suma zmiennych A, B i C wyświetlana w wątku P4 osiągnęła
* określoną wartość (same zmienne mogą mieć wartości dowolne, ale sumujące się do zadanej).
* UWAGA: Wykonanie kodu klasy nie powinno się kończyć blokadą tzn.
* wszystkie wątki powinny zakończyć swoje działanie,
* nawet jeśli watek P4 zakończy się wcześniej.
* Powyższe zachowanie należy zapewnić używając jak najmniejszej liczby semaforów.
* Zestawy zadań (zawierają dwie wartości sumy):
1) 16, 60
2) 21, 56
3) 22, 46
4) 26, 40
5) 30, 36
6) 36, 30
7) 40, 22
8) 46, 26
9) 56, 16
10) 60, 21
11) 16, 46
12) 21, 40
13) 22, 36
14) 26, 30
15) 30, 60
16) 36, 56
17) 40, 16
18) 46, 21
19) 56, 22
20) 60, 26
**********************************/
public class Zad_EP {
private static int A = 0;
private static int B = 0;
private static int C = 3;
private static final Semaphore NONAME = new Semaphore(1, true);
public static void main(String[] args) {
new P1().start();
new P2().start();
new P3().start();
new P4().start();
}
private static final class P1 extends Thread {
@Override
public void run() {
try {
A = 10;
B = B + 5;
C = C + A;
Thread.sleep(0);
System.out.println("Thread P1 is done...");
} catch (InterruptedException ex) {
System.out.println("Ooops...");
Thread.currentThread().interrupt();
throw new RuntimeException(ex);
}
}
}
private static final class P2 extends Thread {
@Override
public void run() {
try {
B = B + C;
A = A + B;
Thread.sleep(0);
System.out.println("Thread P2 is done...");
} catch (InterruptedException ex) {
System.out.println("Ooops...");
Thread.currentThread().interrupt();
throw new RuntimeException(ex);
}
}
}
private static final class P3 extends Thread {
@Override
public void run() {
try {
C = B + 10;
A = 2 * A;
B = B + A;
Thread.sleep(0);
System.out.println("Thread P3 is done...");
} catch (InterruptedException ex) {
System.out.println("Ooops...");
Thread.currentThread().interrupt();
throw new RuntimeException(ex);
}
}
}
private static final class P4 extends Thread {
@Override
public void run() {
try {
System.out.println("Sum result: " + A + " + " + B + " + " + C + " = " + (A + B + C));
Thread.sleep(0);
System.out.println("Thread P4 is done...");
} catch (InterruptedException ex) {
System.out.println("Ooops...");
Thread.currentThread().interrupt();
throw new RuntimeException(ex);
}
}
}
}
Pomógłby mi ktoś wykonać jeden przykład abym zrozumiał na czym polegają semafory?
Z tego co się dowiedziałem należy dodać kilka dodatkowych semaforów.
Niestety byłem chory na zajęciach i mam problem to odrobić.