Kurogane
23-05-2010, 11:16
Salve, devo realizzare la seguente sequenza di terminazione: AABABABABB usando esclusivamente i semafori di java. Ci ho provato ma per come l'ho fatto io arriva alla penultima b e si ferma :muro: non mi viene in mente che logica implementare! Posto il codice per chiedervi dove sbaglio.
import java.util.concurrent.Semaphore;
public class AABABABABB {
private static Semaphore mutexA=new Semaphore(1);
private static Semaphore mutexB=new Semaphore(1);
private static Semaphore sA=new Semaphore(2);
private static Semaphore sB=new Semaphore(0);
/**
* Main
*/
public static void main(String[] args)
{
int a=0, b=0;
for(int i=0; i<10; i++)
{
double n=Math.random();
if(n<=0.5 && a<5 || b==5)
{
new pA("pA"+(a+1)).start();
a++;
}else
{
new pB("pB"+(b+1)).start();
b++;
}
}
}
static class pA extends Thread
{
private String id;
public pA(String id)
{
this.id=id;
}
public void run()
{
try
{
sA.acquire();
mutexA.acquire();
sB.release();
System.out.print(id+" ");
mutexA.release();
}catch(Exception e){}
}
}
static class pB extends Thread
{
private String id;
public pB(String id)
{
this.id=id;
}
public void run()
{
try
{
mutexB.acquire();
sB.acquire();
sB.acquire();
mutexA.acquire();
sA.release();
sB.release(1);
mutexB.release();
System.out.print(id+" ");
mutexA.release();
}catch(Exception e){}
}
}
}
import java.util.concurrent.Semaphore;
public class AABABABABB {
private static Semaphore mutexA=new Semaphore(1);
private static Semaphore mutexB=new Semaphore(1);
private static Semaphore sA=new Semaphore(2);
private static Semaphore sB=new Semaphore(0);
/**
* Main
*/
public static void main(String[] args)
{
int a=0, b=0;
for(int i=0; i<10; i++)
{
double n=Math.random();
if(n<=0.5 && a<5 || b==5)
{
new pA("pA"+(a+1)).start();
a++;
}else
{
new pB("pB"+(b+1)).start();
b++;
}
}
}
static class pA extends Thread
{
private String id;
public pA(String id)
{
this.id=id;
}
public void run()
{
try
{
sA.acquire();
mutexA.acquire();
sB.release();
System.out.print(id+" ");
mutexA.release();
}catch(Exception e){}
}
}
static class pB extends Thread
{
private String id;
public pB(String id)
{
this.id=id;
}
public void run()
{
try
{
mutexB.acquire();
sB.acquire();
sB.acquire();
mutexA.acquire();
sA.release();
sB.release(1);
mutexB.release();
System.out.print(id+" ");
mutexA.release();
}catch(Exception e){}
}
}
}