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 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
|
///////////////////////////////// fichier A.java /////////////////////////////////
class A implements runnable {
int num;
Thread thread;
public A() {
Singleton.incrNum();
}
public synchronized void initNum() {
num = Singleton.getInstance();
Singleton.incrNum();
}
public void run()
{
try {
isReady();
}
catch (InterruptedException e) {
e.printStackTrace();
}
// action a faire.
}
public synchronized void isReady() throws InterruptedException {
if (num != 1) {
wait();
}
else {
notifyAll();
}
}
public static void main(String[] args) {
A a = new A();
a.thread.start();
}
}
////////////////////////////// fichier Singleton.java //////////////////////////////
class Singleton {
private static Singleton instance;
private int num;
private int[] tab;
private Singleton(){
tab = new int[2];
num = 0;
}
public synchronized static Singleton getInstance() {
if (instance == null)
return instance = new Singleton();
return instance;
}
public int getNum() {
return num;
}
public int getTab(int indice) {
return tab[indice];
}
public void setTab(int indice, int val) {
tabPorts[indice] = val;
}
public synchronized void incrNum() {
num++;
}
} |
Partager