Hej, zaczynam zabawę ze współbieżnością w javie. Próbuję zrobić prostą animację na dwóch wątkach (każdy wątek rysuje koło i przesuwa je po ekranie od lewej do prawej). Problemem jest to że oba koła rysują się "na sobie" a ja chciałbym żeby drugie koło "poczekało" aż będzie miało miejsce do narysowania. Synchronizację chciałbym zapewnić za pomocą semaforów z pakietu java.util.concurrent.
import java.awt.*;
import java.applet.*;
public class Anim2 extends Applet
{
private static final long serialVersionUID = -705555689585339843L;
//public Thread thread;
Image image;
Graphics gc;
int x, y, r;
int w, h;
Sam sa= new Sam();
Sam ss=new Sam();
public void init()
{
// thread = null;
sa.start();
ss.start();
this.setBounds(0, 0, 500, 80);
w=getSize().width;
h=getSize().height;
x=0;
y = h/6;
r = 45;
image=createImage(w,h);
gc = image.getGraphics();
gc.fillRect(0, 0, w, h);
}
public void paint(Graphics g){
g.drawImage(image,0,0,this);
g = image.getGraphics();
g.setColor(Color.white);
g.fillRect(0,0,w,h);
g.setColor(Color.black);
g.fillOval(sa.x, y, r, r);
g.fillOval(ss.x, y, r, r);
repaint();
}
public void update(Graphics g){
paint(g);
}
}
import java.awt.Color;
import java.awt.Graphics;
public class Sam implements Runnable {
Graphics gc;
public Thread thread;
int x, y;
public Sam(){
thread=null;
x=0;
y=0;
}
public void start()
{
if (thread == null) {
thread = new Thread(this);
thread.start();
}
}
public void stop()
{
if (thread != null){
thread = null;
}
}
public void run() {
while(thread!=null)
{
x ++;
if(x == 500) x = (int) (-80/1.5);
try {
Thread.sleep(5);
} catch(InterruptedException e){}
}
}
}