2012-12-23 12:04:56Morris
[JAVA][Thread] 試寫
做個糞作來玩玩。
Demo 影片:http://www.youtube.com/watch?v=bahAEMYQr5o&feature=youtu.be
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.*;
public class ThreadDemo extends JFrame {
Obj[] CIR = new Obj[10];
Thread[] Trd = new Thread[10];
public ThreadDemo() {
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(600, 500);
setVisible(true);
setResizable(false);
setTitle("Demo");
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
CIR[i*3+j] = new Obj(i*100+100, j*100+100, i*3+j);
Trd[i*3+j] = new Thread(CIR[i*3+j]);
}
}
for(int i = 0; i < 9; i++) {
Trd[i].start();
}
}
public void paint(Graphics g) {
g.setColor(Color.BLACK);
g.fillRect(0, 0, 500, 500);
}
public static void main(String[] args) {
ThreadDemo t1 = new ThreadDemo();
}
class Obj implements Runnable {
double x, y, vx, vy;
int idx;
public Obj(int x, int y, int idx) {
this.x = x;
this.y = y;
this.idx = idx;
vx = Math.random()*8+1;
vy = Math.random()*8+1;
if(Math.random() < 0.5)
vx = -vx;
if(Math.random() < 0.5)
vy = -vy;
}
public void run() {
Graphics g = getGraphics();
double dist, theta;
double fx, fy, tx, ty;
while(true) {
try {
Thread.sleep(50);
g.setColor(Color.BLACK);
for(int i = 1; i <= 30; i++)
g.drawOval((int)x, (int)y, i, i);
x += vx;
y += vy;
if(x+30 >= 490 || x-30 < -20) {
x -= vx;
vx = -vx;
}
if(y+30 >= 470 || y-30 < 0) {
y -= vy;
vy = -vy;
}
for(int i = 0; i < 9; i++) {
if(i == idx)
continue;
dist = Math.sqrt(Math.pow(CIR[i].x-x, 2)+Math.pow(CIR[i].y-y, 2));
if(dist < 60) {
fx = CIR[i].x-x;
fy = CIR[i].y-y;
theta = Math.acos((fx*vx+fy*vy)/Math.sqrt(vx*vx+vy*vy)/Math.sqrt(fx*fx+fy*fy));
theta = -2*(theta+0.0001);
tx = vx*Math.cos(theta) - vy*Math.sin(theta);
ty = vx*Math.sin(theta) + vy*Math.cos(theta);
x -= vx;
y -= vy;
vx = -tx;
vy = -ty;
CIR[i].vx *= -1;
CIR[i].vy *= -1;
/*x += vx;
y += vy;*/
//break;
}
}
g.setColor(Color.GREEN);
g.fillOval((int)x, (int)y, 30, 30);
} catch(InterruptedException e) {
Thread.interrupted();
}
}
}
}
}