多线程同步(三)

通过对Audio代码的研究,我对多线程有了更深的认识:

1。首先,你不可以去预测,cpu执行线程的顺序及时间点,所以你必须小心谨慎。
2。因为手机这样资源短缺的设备,我们时刻要考虑,什么样的操作比较浪费资源和时间(比如I/O操作),没办法的时候,只能采用同步机制,尽管这样会影响性能。
3。当我们要循环做某个动作时,我们可以在一个线程的run()中,用一个while循环,比如Bouncing Ball MIDlet应用程序中的小球不停的运动现象,就是用了一个while语句:

public void run() {
 // System.out.println("starting... " + this);
 int right = left + width;
 int bottom = top + height;

 while (!stop) {

     ballSize = radius * 2;

     // calculate a direction of the ball as an integer in the range
     // -2 .. 2 (excluding 0)
     int direction = deltaX + deltaY;
     if (direction == 0) direction = deltaX + 2*deltaY;

     // is the current position colliding with any wall
     int collision = 0;
     if (posX <= left || posX >= right) collision++;
     if (posY <= top || posY >= bottom) collision += 2;

     // change the direction appropriately if there was a collision
     if (collision != 0) {
  try {
      javax.microedition.media.Manager.playTone(note, 100/*ms*/,100);
  } catch (Exception ex) {
      System.out.println("failed to play tone");
  }

  collision = (collision - 1) * 2;

  deltaX = matrix[direction+2][collision];
  deltaY = matrix[direction+2][collision+1];
     }

     // calculate the new position and queue a repaint
     posX = posX + deltaX;
     posY = posY + deltaY;

     if (doRepaint) {
  canvas.repaint();
     }

     // use the delay to control the speed of the ball
     // if the MIDlet is paused, keep on waiting
     do {
  try {
      // if paused, always wait 100 millis,
      // regardless of ball speed
      Thread.sleep(paused?100:delay);
  } catch (InterruptedException e) {}
     } while (paused && !stop);
 }
    }

还有就是,背景音乐的循环播放,并不是放在线程里去实现的,而是利用它本身的一个函数,比如在MixCanvas.java中:

private void createWavPlayer() {
 try {
     if (wavPlayer == null) {
  if (MixTest.wavUrl.startsWith("resource")) {
      int idx = MixTest.wavUrl.indexOf(':');
      String loc = MixTest.wavUrl.substring(idx+1);
      InputStream is = getClass().getResourceAsStream(loc);
      String ctype = guessContentType(MixTest.wavUrl);
      wavPlayer = Manager.createPlayer(is, ctype);
  } else {
      wavPlayer = Manager.createPlayer(MixTest.wavUrl);
  }
  wavPlayer.setLoopCount(-1);
     }
     if(stopSound) {
  return;
     }
     wavPlayer.start();
 } catch (Exception ex) {
     // ex.printStackTrace();
     if (wavPlayer != null) {
  wavPlayer.close();
  wavPlayer = null;
     }
     parentDisplay.setCurrent(alert);
 }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值