Non sto usando i synchronize, sto usando Lock e Condition, vorrei che qualcuno guardi il codice, non riesco proprio a rendermi conto da solo dell'errore
Eccoli
package esercizio.tvLC;
import java.util.LinkedList;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Sala {
private TVLC tv;
private LinkedList<Thread> ll=new LinkedList<>();
final int MAX=30;
private int inside=0;
private Lock l;
private Condition c;
public Sala(){
tv=new TVLC();
l=new ReentrantLock();
c=l.newCondition();
}
public void entra()throws InterruptedException{
l.lock();
try{
ll.addLast(Thread.currentThread());
while(inside>=MAX && Thread.currentThread()!=ll.getFirst()){
c.await();
}
ll.removeFirst();
inside++;
}
finally{l.unlock();}
}
public void esci()throws InterruptedException{
l.lock();
try{
inside--;
c.signalAll();
}
finally{l.unlock();}
}
public TVLC getTv(){
return tv;
}
}
CLASSE TVLC
package esercizio.tvLC;
import java.util.concurrent.locks.*;
public class TVLC {
final int NUM_CHANNEL=8;
private Lock l=new ReentrantLock();
private Condition [] c;
private int numSpett=0, canale=0;
private int [] waitChannel=new int [8];
public TVLC(){
c=new Condition[NUM_CHANNEL];
for(int i=0; i<c.length; i++ )
c[i]=l.newCondition();
}
public void iniziaVisione(int channel) throws InterruptedException{
l.lock();
try{
if(numSpett==0){
canale=channel;
numSpett++;
}
else if(canale==channel){
numSpett++;
}
else{
waitChannel[channel]++;
while(canale!=channel)c[channel].await();
waitChannel[channel]--;
numSpett++;
}
}
finally{l.unlock();}
}
public void fineVisione()throws InterruptedException{
l.lock();
try{
numSpett--;
if(numSpett==0){
int ch=maxWaiting();
canale=ch;
c[canale].signalAll();
}
}finally{
l.unlock();}
}
private int maxWaiting() {
// TODO Auto-generated method stub
int max=0;
for(int i=1; i<waitChannel.length;i++)
if(waitChannel[i]>waitChannel[max])max=i;
return max;
}
}
CLASSE PERSONA
package esercizio.tvLC;
import java.util.Random;
import java.util.concurrent.TimeUnit;
public class Persona extends Thread{
Sala s;
TVLC tv;
Random r=new Random();
public Persona(Sala s1){
s=s1;
tv=s.getTv();
}
public void run(){
while(true){
try {
int c=r.nextInt(tv.NUM_CHANNEL);
s.entra();
tv.iniziaVisione(c);
guarda(c);
System.out.println(getName() + " sta guardando canale "+ c);
tv.fineVisione();
s.esci();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
}
}
}
private void guarda(int c) throws InterruptedException {
// TODO Auto-generated method stub
System.out.println(getName() + " sta guardando canale "+ c);
TimeUnit.SECONDS.wait(r.nextInt(270)+30);
}
}
Ed il main di test
package esercizio.tvLC;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Sala s=new Sala();
Persona [] p=new Persona[100];
for(int i=0; i<p.length; i++)
p[i]=new Persona(s);
for(int i=0; i<p.length; i++)
p[i].start();
}
}