Thread.sleep(timeOut);
} catch(InterruptedException e) {
interrupt();
}```
Warum verwendest du nicht
```try {
Thread.sleep(timeOut);
} catch(InterruptedException e) {
Thread.currentThread().interrupt();
}```?[/QUOTE]
[QUOTE=Unregistered;76387]ich würde eher fragen warum gewohnheitsmäßig Thread.sleep() obwohl auf alles andere dank extends Thread direkt zugegriffen wird
man könnte also eher fragen : warum Thread.sleep() statt nur sleep() ?[/QUOTE]
Weil "Thread.sleep()" nur eine Zeile ist und ich mir damit einen synchronizrd-Block für "wait(timeOut)" spare und "Thread.sleep()", weil "sleep()" alleine afaik eine Warnung ergibt (static-method-call in non-static-context)... aber "sleep()" hab ich grade mal ausprobiert, eine Warnung kommt da nicht. Also ja, ich verwende "Thread.sleep()" gewohnheitsmäßig.
Stand in deinem Beitrag die Begründung für interrupt()? Das Zitat meines Beitrages lässt darauf schließen, allerdings kann ich die Antwort nicht finden :eek:
Mit dem Thread.sleep() gehe ich vollkommen mit dir konform, das ist man so einfach gewöhnt.
[QUOTE=cmrudolph]Stand in deinem Beitrag die Begründung für interrupt()? Das Zitat meines Beitrages lässt darauf schließen, allerdings kann ich die Antwort nicht finden :eek:[/QUOTE]Wieso? Was muss da noch begründet werden? Innerhalb eines Threads ist dieser Thread der “current Thread”, da braucht man die statische Methode nicht. Diese statischen Methoden sind eher was für Runnables. Warum da ein “interrupt()” hingehört, steht hoffentlich nicht zur Diskussion: Die Exception kann ihre Ursache in ganz anderen Threads haben, wodurch dieser Thread längst noch nicht unterbrochen wäre und ohne “interrupt()” nun möglicherweise einen Deadlock verursacht, z.B. wenn der Thread, der die Exception geworfen hat nun auf das Ende dieser Threads wartet.
Hat das mal einer gelesen, was da im alten Forum geschrieben wurde?
Der TO aus unserm Nachbarland (“ich steh an” haha) durfte sich dann auch nicht wundern, dass wir an seinem Code vorbei schreiben,
wenn er den hier nicht postet.
Die Klasse “Daten” scheint dann die Klasse zu sein, die Daten von Com-Ports liest…und…boah…nee…
Erbrochenes hat mehr Struktur.
*** Edit ***
nach allem hätte ich das wahrscheinlich etwa so gelöst:
wieder nicht der Code des TO
[spoiler]```import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class RingbufferTest {
public static void main(String[] args) throws Exception {
final int NUMPORTS = 3;
BlockingQueue<HWDataSet> queue = new ArrayBlockingQueue<HWDataSet>(NUMPORTS);
HWData[] src = new HWData[NUMPORTS];
for (int i = 0; i < src.length; i++) {
src** = new HWData("COM"+(i+1));
}
Timer timer = new Timer();
Write_Task producer = new Write_Task(queue,src);
Read_Task consumer = new Read_Task(queue);
timer.scheduleAtFixedRate(new Task(producer,consumer), 500, 100);
Thread.sleep(10000);
timer.cancel();
for (int i = 0; i < src.length; i++) {
src**.close_conn();
}
}
}
class Task extends TimerTask
{
protected Write_Task producer;
protected Read_Task consumer;
public Task(Write_Task producer,Read_Task consumer) {
this.producer = producer;
this.consumer = consumer;
} @Override public void run()
{
new Thread(producer).start();
new Thread(consumer).start();
}
}
class HWDataSet {
long time;
int port;
float temperature;
float poti;
float sinus;
public HWDataSet(long time,int port,float temperature, float poti, float sinus){
this.time=time;
this.port=port;
this.temperature=temperature;
this.poti=poti;
this.sinus=sinus;
}
public long getTime() {
return time;
}
public int getPort() {
return port;
}
public double getTemperature() {
return temperature;
}
public double getPoti() {
return poti;
}
public double getSinus() {
return sinus;
}
public String toString(){
return String.format("Time %d Port %d Temperature %.2f Poti %.2f Sinus %.2f",
time, port, temperature, poti, sinus
);
}
}
class HWData{
private static int portcount = 0;
private int port;
private String com;
// private Prot my_prot = new Prot(); // neue Klasse anlegen zum ringebuffer realisieren diese ist nur für die communication zuständig
public HWData(String COM_PORT) {
portcount++;
port = portcount;
com = COM_PORT;
System.out.printf("%d Port %s opened %n",port,com);
//my_prot.prot_init(COM_PORT);
}
public HWDataSet readHWData() {
// <--- hier lokal die variabeln von oben anlegen
float fAN1=0f; // fAN1=my_prot.prot_get_AN1();
float fAN2=0f; // fAN2=my_prot.prot_get_AN2();
float fTEMP=0f;// fTEMP=my_prot.prot_get_temp();
try {
fAN1 = (float ) Math.random()*10;
fAN2 = (float ) Math.random()*10+10;
fTEMP = (float ) Math.random()*10+20;
// } catch (ProtException e) {
} catch (Exception e) {
e.printStackTrace();
}
return (new HWDataSet(System.nanoTime(),port,fAN1,fAN2,fTEMP));
}
public void close_conn() {
System.out.printf("%d Port %s closed %n",port,com);
//my_prot.prot_close();
}
}
public static void main(String[] args) throws Exception {
final int NUMPORTS = 10;
final int INTERVAL = 500;
// circular buffer (queue)
BlockingQueue<HWDataSet> queue = new ArrayBlockingQueue<HWDataSet>(NUMPORTS);
// Array of hardware connectors (emulation)
HWData[] src = new HWData[NUMPORTS];
for (int i = 0; i < src.length; i++) {
src** = new HWData(String.format("%s%d", "COM",i+1));
}
// Producer and Consumer for circular buffer
Write_Task producer = new Write_Task(queue,src);
Read_Task consumer = new Read_Task(queue);
// let timer task repeat threading (hopefully) about 50 times
// (on my system with 10 ports intervals below 20 mills. are difficult)
Timer timer = new Timer();
timer.scheduleAtFixedRate(new Task(producer,consumer), INTERVAL, INTERVAL);
Thread.sleep(50*INTERVAL);
timer.cancel();
// wait for last producer action to finish, before closing connections
Thread.sleep(2);
for (int i = 0; i < src.length; i++) {
src**.close_conn();
}
}
}
class Task extends TimerTask
{
/**
* starts producer thread
* waits for thread to die (join) and then
* starts consumer thread
* and also wait for this thread to die
* otherwise the next producer would not be able to put all data in the buffer.
* Anyhow, if intervals are to short, some data is lost in one or the other way.
* A larger queue might help to certain extent.
*/
protected Write_Task producer;
protected Read_Task consumer;
public Task(Write_Task producer,Read_Task consumer) {
this.producer = producer;
this.consumer = consumer;
} @Override public void run()
{
Thread t1=new Thread(producer);
Thread t2=new Thread(consumer);
try {
t1.start();
t1.join();
t2.start();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class HWDataSet {
// Data set returned by the hardware connectors
long time;
int port;
float temperature;
float poti;
float sinus;
public HWDataSet(long time,int port,float temperature, float poti, float sinus){
this.time=time;
this.port=port;
this.temperature=temperature;
this.poti=poti;
this.sinus=sinus;
}
public long getTime() {
return time;
}
public int getPort() {
return port;
}
public double getTemperature() {
return temperature;
}
public double getPoti() {
return poti;
}
public double getSinus() {
return sinus;
}
public String toString(){
DateFormat formatter = new SimpleDateFormat("HH:mm:ss:SSS");
return String.format("Time %s Port %2d Temperature %.2f Poti %.2f Sinus %.2f",
formatter.format(time), port, temperature, poti, sinus
);
}
}
class HWData{
/**
* This class is responsible for reading from the hardware.
* Hardware connection is build up for port COM_PORT when calling the constructor.
* Reading data from the port is initiated by the Method readHWData() which
* returns a fixed set of data as an instance of class HWDataSet.
* Call Method close_conn() to close hardware connection.
*
* Just simulation as the users class “Prot” is unknown
*/
private static int portcount = 0;
private int port;
private String com;
private boolean open=false; // for testing
// private Prot my_prot = new Prot();
public HWData(String COM_PORT) {
portcount++;
port = portcount;
com = COM_PORT;
open = true; //my_prot.prot_init(COM_PORT);
System.out.printf(“Port %2d %-5s opened %n”,port,com);// for testing
}
public HWDataSet readHWData() {
// reading data from the hardware and returning an instance of HWDataSet
// (emulation for testing)
float fAN1=0f;
float fAN2=0f;
float fTEMP=0f;
try {
if (!open) throw new Exception(“Error: Port closed”); // for testing
fAN1 = (float ) Math.random()*10; // fAN1=my_prot.prot_get_poti();
fAN2 = (float ) Math.random()*10+10;// fAN2=my_prot.prot_get_AN2();
fTEMP = (float ) Math.random()*10+20;// fTEMP=my_prot.prot_get_temp();
} catch (Exception e) { // for testing
// } catch (ProtException e) {
e.printStackTrace();
}
return (new HWDataSet(System.currentTimeMillis(),port,fTEMP,fAN1,fAN2));
}
public void close_conn() {
open=false; //my_prot.prot_close();
System.out.printf(“Port %2d %-5s closed %n”,port,com); // for testing
}
}
class Write_Task implements Runnable {
/**
* Producer
* Initiates reading data from sources (src) and puts the results in a circular buffer (queue)
*
*/
protected BlockingQueue queue = null;
HWData[] src;
public Write_Task(BlockingQueue queue,HWData[] src) {
this.queue = queue;
this.src = src;
}
public void run() {
try {
for (int i=0; i < src.length; i++){
queue.put(src**.readHWData());
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class Read_Task implements Runnable {
/**
* Consumer
* Prints all data available in the circular buffer (queue)
*/
protected BlockingQueue queue = null;
protected static int count=0;
public Read_Task(BlockingQueue<HWDataSet> queue) {
this.queue = queue;
}
public void run() {
try {
while (!queue.isEmpty()) {
System.out.println(queue.take());
}
System.out.println(++count);
} catch (InterruptedException e) {
e.printStackTrace();
}
}