线程的基本应用--续
今天在昨天的基础上新增加了一些线程的知识,包括:线程的监听和线程的控制。
线程的监听即是在开始start()主要运行的线程之前,先开始一个监听的线程,类似鼠标监听器。在监听线程中可以设置小球间的碰撞。
以下是程序代码:
1.界面类中的代码
// 创建监听器对象(匿名内部类)ActionListener alis = new ActionListener() {public void actionPerformed(ActionEvent e) {String command = e.getActionCommand();// 启动监视线程BallListener blis = new BallListener(list,getUI());blis.start();if (command.equals("开始")) {panel.paint(g);Ball.initBall();// 创建一个小球对象Ball ball = new Ball(getUI());ball.start();list.add(ball);//将开始按钮设为 暂停jbu.setText("暂停");} }}public class BallListener extends Thread {// 创建队列以存放小球对象ArrayList<Ball> alis;// 得到的画布对象Graphics g;BallUI ballui;/** * 构造方法 * * @param alis * 传入存放小球的队列对象 */public BallListener(ArrayList<Ball> alis,BallUI ballui) {this.alis = alis;this.ballui = ballui;// 由窗体对象得到画布对象g = ballui.panel.getGraphics();}public void run() {while (!Ball.isStop) {while (!Ball.isPause) {//依次比较两个小球对象for (int i = 0; i < alis.size() ; i++) {for(int j = i+1; j< alis.size() ; j++){Ball b = alis.get(i);Ball b1 = alis.get(j);double distance =Math.hypot( ((b.x+b.size/2)-(b1.x+b1.size/2)),((b.y+b.size/2)-(b1.y+b1.size/2)));if(distance <= b.size){int tempx,tempy;tempx = b.x;b.x = b1.x;b1.x = tempx;tempy = b.y;b.y = b1.y;b1.y = tempy;// 擦除球g.setColor(ballui.panel.getBackground());g.fillOval(b.x, b.y, b.size, b.size);g.fillOval(b1.x, b1.y, b1.size, b1.size);//g.setColor(Color.BLACK);//g.fillOval(b.x = b.x + b.dx, b.y = b.y + b.dy, b.size, b.size);//g.fillOval(b1.x = b1.x + b1.dx, b1.y = b1.y + b1.dy, b.size, b.size);}}}try {Thread.sleep(10);} catch (Exception e) {e.printStackTrace();}}try {Thread.sleep(10);} catch (Exception e1) {e1.printStackTrace();}}}}public void move() {while (!isStop) {while (!isPause) {// 擦除球g.setColor(ballui.panel.getBackground());g.fillOval(x, y, size, size);// 画球g.setColor(Color.BLACK);if ((x < (425-size) && x > 0) && (y > 0 && y < (400-size))) {// 如果球未碰边g.fillOval(x = x + dx, y = y + dy, 30, 30);} else if (!(x < (425-size) && x > 0) && !(y > 0 && y < (400-size))) {// 如果球同时碰2两条边dx = -dx;dy = -dy;g.fillOval(x = x + dx, y = y + dy, 30, 30);} else if ((x < (425-size) && x > 0) && !(y > 0 && y < (400-size))) {// 如果球碰竖边dy = -dy;g.fillOval(x = x + dx, y = y + dy, 30, 30);} else if (!(x < (425-size) && x > 0) && (y > 0 && y < (400-size))) {// 如果球碰横边dx = -dx;g.fillOval(x = x + dx, y = y + dy, 30, 30);}try {sleep(20);} catch (Exception e1) {e1.printStackTrace();}}try {Thread.sleep(1);// 沉睡时间,暂停时的休眠} catch (Exception ef) {ef.printStackTrace();}}}/** * 暂停线程的方法 */public static void pauseThread() {isPause = true;}/** * 继续线程的方法 */public static void resumeThread() {isPause = false;}/** * 停止线程的方法 */public static void stopThread() {isPause = true;isStop = true;}/** * 初始化线程的方法 */public static void initBall() {isPause = false;isStop = false;}