129 lines
2.5 KiB
Java
129 lines
2.5 KiB
Java
/*
|
|
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
|
|
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
|
|
*/
|
|
|
|
package bandit.Model;
|
|
|
|
import java.util.concurrent.ExecutorService;
|
|
import java.util.concurrent.Executors;
|
|
import java.util.concurrent.Flow.Subscriber;
|
|
import java.util.concurrent.SubmissionPublisher;
|
|
import java.util.logging.Logger;
|
|
import bandit.util.OhmLogger;
|
|
|
|
|
|
/**
|
|
*
|
|
* @author Schuhmann
|
|
*/
|
|
public class Wuerfel implements Runnable // Callable
|
|
{
|
|
private static Logger lg = OhmLogger.getLogger(); //Logger sollten immer static sein da sie für alle instanzen loggs ausführen
|
|
private WuerfelData data;
|
|
private volatile boolean laufend;
|
|
private ExecutorService eService;
|
|
private final Object LOCK;
|
|
private SubmissionPublisher<WuerfelData> wertPublisher;
|
|
|
|
public Wuerfel(int id)
|
|
{
|
|
data = new WuerfelData(id, 0);
|
|
laufend = false;
|
|
eService = null;
|
|
wertPublisher = new SubmissionPublisher<>();
|
|
LOCK = new Object();
|
|
}
|
|
|
|
public void addWertSubscription(Subscriber<WuerfelData> subscriber)
|
|
{
|
|
wertPublisher.subscribe(subscriber);
|
|
}
|
|
|
|
public void start()
|
|
{
|
|
synchronized (this) {
|
|
laufend = true;
|
|
}
|
|
|
|
if (eService == null)
|
|
{
|
|
eService = Executors.newSingleThreadExecutor();
|
|
eService.execute(this);
|
|
}
|
|
synchronized (LOCK)
|
|
{
|
|
LOCK.notifyAll();
|
|
}
|
|
}
|
|
|
|
public void stop()
|
|
{
|
|
synchronized(this){
|
|
laufend = false;
|
|
}
|
|
}
|
|
|
|
@Override
|
|
public void run()
|
|
{
|
|
lg.fine("Run "+ data.getId());
|
|
while (true)
|
|
{
|
|
|
|
while (!laufend)
|
|
{
|
|
synchronized (LOCK)
|
|
{
|
|
try
|
|
{
|
|
lg.fine("Stop " + data.getId());
|
|
LOCK.wait();
|
|
}
|
|
catch (InterruptedException ex)
|
|
{
|
|
lg.warning(ex.toString());
|
|
}
|
|
}
|
|
}
|
|
|
|
try
|
|
{
|
|
Thread.sleep(100);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
System.err.println(ex);
|
|
}
|
|
|
|
if(laufend){
|
|
this.berechneWert();
|
|
wertPublisher.submit(data);
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* berechnet den Wert für jede itteration
|
|
*/
|
|
private synchronized void berechneWert()
|
|
{
|
|
data.setValue((int) (1 + 6*Math.random()));
|
|
// if(data.getValue() < 6){
|
|
// data.setValue(data.getValue()+1);
|
|
// }
|
|
// else{
|
|
// data.setValue(0);
|
|
//
|
|
// }
|
|
|
|
}
|
|
|
|
public synchronized int getValue(){
|
|
return data.getValue();
|
|
}
|
|
|
|
}
|
|
|
|
|