Kompletter Quellcode Parkplatzproblem gelöst
// Monitore (Multithreading Demo) fuer das Projektsudium 1997
// von Timo Gronwald
import java.applet.Applet;
import java.awt.*;
public class multi extends Applet
{
// Applikation start
public static void main (String args[])
{
Frame Fenster = new Frame("Beispiel fuer 'Syncronized'");
Fenster.add("Center",new CPanel(""));
Fenster.resize(200,400);
Fenster.show();
}
// Applet start
public void init()
{
resize(200,400);
setLayout(new BorderLayout());
add("Center",new CPanel(""));
}
}
class CPanel extends Panel
{
public TextArea Ausgabe;
public CPanel(String text)
// Komponentendarstellung und Threads start
{
Ausgabe = new TextArea(22,20);
setLayout(new FlowLayout());
add(Ausgabe);
Stellplatz s = new Stellplatz();
Eingang in = new Eingang(s,Ausgabe);
Ausgang out = new Ausgang(s,Ausgabe);
in.start();
out.start();
}
}
// Thread 1 : 10 Durchgaenge "Parken" wenn Parkplatz frei
class Eingang extends Thread
{
Stellplatz s;
TextArea t;
public Eingang (Stellplatz s, TextArea t)
{
this.s = s;
this.t = t;
}
public void run()
{
for (int i=0; i<10; i++)
{
s.put(t,i);
try
{
sleep((int)(Math.random()*1000));
}
catch (InterruptedException e) {}
}
}
}
// Thread 2 : 10 Durchgaenge "Auto abholen" wenn Parkplatz besetzt
class Ausgang extends Thread
{
Stellplatz s;
TextArea t;
public Ausgang (Stellplatz s, TextArea t)
{
this.s = s;
this.t = t;
}
public void run()
{
for (int i=0; i<10; i++)
{
s.get(t);
try
{
sleep((int)(Math.random()*1000));
}
catch (InterruptedException e) {}
}
}
}
// Methoden "Parken" (= put) und "Abholen" (= get)
class Stellplatz
{
int puffer;
boolean vorhanden = false;
public synchronized void put(TextArea t, int nummer)
{
// Wenn Parkplatz besetzt, dann nicht parken!
if (vorhanden) try
{
wait();
}
catch (InterruptedException e) {}
t.appendText("Eingetragen: "+nummer+"\n");
puffer = nummer;
vorhanden = true;
notify();
}
public synchronized void get(TextArea t)
{
// Wenn kein "Auto da" auf Auto warten
if (!vorhanden) try
{
wait();
}
catch (InterruptedException e) {}
t.appendText("Abgeholt: "+puffer+"\n");
vorhanden = false;
notify();
}
}