有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

用线程同时运行两个对象的java?

我正在尝试运行一个对象,它使用线程在自身上产生正弦波。当我尝试用线程播放对象时,它会播放第一个线程,直到它完成,然后播放第二个线程。我不知道这个线程有什么问题,因为我不熟悉java中的线程。谢谢你的帮助和回应

代码如下:

package dreamBeats;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;

public class Tone extends Thread{

    static int length;
    static int wavelength;

   protected static final int SAMPLE_RATE = 16 * 1024;

public Tone(int time, int wave) throws LineUnavailableException{
       final AudioFormat af = new AudioFormat(SAMPLE_RATE, 8, 1, true, true);
       SourceDataLine line = AudioSystem.getSourceDataLine(af);
       line.open(af, SAMPLE_RATE);
       line.start();

       for(double freq = wave; freq <= wave*2; freq += freq/4)  {
           byte [] toneBuffer = createSinWaveBuffer(freq, time);
           int count = line.write(toneBuffer, 0, toneBuffer.length);
       }

       line.drain();
       line.close();

       length = time;
       wavelength = wave;
   }

//makes a sine wave buffer
   public static byte[] createSinWaveBuffer(double freq, int ms) {
       int samples = (int)((ms * SAMPLE_RATE) / 1000);
       byte[] output = new byte[samples];
           //
       double period = (double)SAMPLE_RATE / freq;
       for (int i = 0; i < output.length; i++) {
           double angle = 2.0 * Math.PI * i / period;
           output[i] = (byte)(Math.sin(angle) * 127f);  }

       return output;
   }
// run the tone object
   public void run(){

        try {

        Tone(length, wavelength);

        } catch (LineUnavailableException e) {}
      }
//create the threads and run them during one another
   public static void main(String[] args) throws LineUnavailableException, InterruptedException {
       Thread t1 = new Thread (new Tone(1000, 200));
       Thread t2 = new Thread (new Tone(1000, 500));
       t1.start();
       t2.start();
    }



}

共 (1) 个答案

  1. # 1 楼答案

    线程是很棘手的,并且在运行期间不总是能够判断哪个线程具有优先级,因为它依赖于JVM。以运行线程t1和t2的方式,不能保证t1总是在t2之前执行,反之亦然。我建议使用wait和notify来管理线程执行