标签:
Code
?
import java.util.Random;
import java.awt.*; //引入的包,Graphics所在的包
import java.applet.*;
?
class Particle {
protected int x;
protected int y;
protected final Random rng = new Random();
?
public Particle(int initialX, int initialY) {
x = initialX; //initial position
y = initialY;
}
?
//同步机制使用synchronized关键字 -- 原子操作
public synchronized void move() {
x += rng.nextInt(10) - 5;
y += rng.nextInt(20) - 10;
}
?
//Graphics抽象类,它的对象是用来传给paint()方法作为画笔的
public void draw(Graphics g) {
int lx, ly;
//代码块 atomic
synchronized (this) { lx = x; ly = y; }
//g.drawRect(lx, ly, 10, 10);
g.drawOval(lx, ly, 10, 15);
}
}
?
//Canvas: 画布
class ParticleCanvas extends Canvas {
private Particle[] particles = new Particle[0];
?
ParticleCanvas(int size) { //Canvas size
setSize(new Dimension(size, size));
}
?
// intended to be called by applet
protected synchronized void setParticles(Particle[] ps) {
if (ps == null)
throw new IllegalArgumentException("Cannot set null");
?
particles = ps;
}
?
protected synchronized Particle[] getParticles() {
return particles;
}
?
public void paint(Graphics g) {
// override Canvas.paint
Particle[] ps = getParticles();
?
for (int i = 0; i < ps.length; ++i)
ps[i].draw(g);
}
}
?
public class ParticleApplet extends Applet {
protected Thread[] threads = null; // null when not running
protected final ParticleCanvas canvas = new ParticleCanvas(100);
public void init() { add(canvas); }
?
//Runnable runnable = new Runnable(){ public void run(){ } }
//相當於是:
// class $1 implements Runnable { public void run() { } }
protected Thread makeThread(final Particle p) { // utility
//内部类
Runnable runloop = new Runnable() {
public void run() {
try {
for(;;) {
p.move();
canvas.repaint();
Thread.sleep(100); // 100msec is arbitrary
}
}
?
catch (InterruptedException e) { return; }
}
};
?
return new Thread(runloop);
}
?
public synchronized void start() {
int n = 10; // just for demo, n -- particle nums
?
if (threads == null) { // bypass if already started
Particle[] particles = new Particle[n];
?
for (int i = 0; i < n; ++i)
particles[i] = new Particle(50, 50);
?
canvas.setParticles(particles);
threads = new Thread[n];
?
for (int i = 0; i < n; ++i) {
threads[i] = makeThread(particles[i]);
threads[i].start();
}
}
}
?
public synchronized void stop() {
if (threads != null) { // bypass if already stopped
?
for (int i = 0; i < threads.length; ++i)
threads[i].interrupt();
?
threads = null;
}
}
}
?
标签:
原文地址:http://www.cnblogs.com/westRiver/p/4401900.html