Hej.
Mam takie rozwiązanie problemu palaczy i chciałbym dorobić do tego jakąś prostą animację.
Dałoby rade w jakiś prosty sposób przerobić ten kod żeby nie gryzł się z GUI? Czy raczej trzeba trochę pozmieniać?
import java.util.ArrayList;
import java.util.Random;
import javax.swing.SwingUtilities;
class Agent extends Thread {
private Stol stol;
public Agent(Stol s) {
stol = s;
}
@Override
public void run() {
while (true) {
try {
Thread.sleep(1000);
} catch (Exception e) {
}
stol.setZasobyAgenta();
System.out.println("Agent kladzie " + stol.getZasobyAgenta());
pause();
}
}
public synchronized void Obudz() {
try {
notify();
} catch (Exception e) {
}
}
public synchronized void pause() {
try {
this.wait();
} catch (Exception e) {
}
}
}
class Palacz extends Thread {
private Stol stol = new Stol();
private String zasob;
private int liczbaZasobow;
private Agent agent;
public Palacz(Stol s, int ileZasobow, String name, Agent a) {
liczbaZasobow = ileZasobow;
this.stol = s;
setName(name);
agent = a;
}
@Override
public void run() {
while (true) {
zasob = stol.getZasob(liczbaZasobow);
if (!stol.maZasob(zasob) && !stol.Pusty()) {
System.out.println(getName() + " ma " + zasob + ".");
try {
Pal();
System.out.println(getName() + " budzi Agenta");
agent.Obudz();
} catch (Exception e) {
}
}
}
}
public synchronized void Pal() throws Exception {
System.out.println(getName() + " pali.");
Thread.sleep(5000);
System.out.println(getName() + " skonczyl");
}
}
class Stol {
private ArrayList<String> wszystkieZasoby = new ArrayList<String>();
private ArrayList<String> zasobyAgenta = new ArrayList<String>();
public Stol() {
wszystkieZasoby.add("tyton");
wszystkieZasoby.add("papier");
wszystkieZasoby.add("zapalki");
}
public void setZasobyAgenta() {
Random random = new Random();
zasobyAgenta.clear();
ArrayList<String> kopiujZasoy = (ArrayList<String>) wszystkieZasoby.clone();
int zasob1 = random.nextInt(kopiujZasoy.size());
zasobyAgenta.add(kopiujZasoy.get(zasob1));
kopiujZasoy.remove(zasob1);
int zasob2 = random.nextInt(kopiujZasoy.size());
zasobyAgenta.add(kopiujZasoy.get(zasob2));
}
public boolean Pusty() {
return (zasobyAgenta.size() == 0);
}
public synchronized String getZasobyAgenta() {
notifyAll();
return zasobyAgenta.toString();
}
public synchronized String getZasob(int zasob) {
try {
this.wait();
} catch (Exception e) {
}
return wszystkieZasoby.get(zasob);
}
public boolean maZasob(String nazwaZas) //
{
return (zasobyAgenta.contains(nazwaZas));
}
public synchronized void pause() {
try {
this.wait();
} catch (Exception e) {
}
}
}
public class Main {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
Stol stol = new Stol();
Agent agent = new Agent(stol);
agent.start();
for (int i = 0; i < 3; i++) {
Palacz palacz = new Palacz(stol, i, "Palacz " + Integer.toString(i + 1), agent);
palacz.start();
}
}
});
}
}