我正在尝试运行一个使用线程在自身上产生正弦波的对象。当我尝试用线程互相播放对象时,它会播放第一个线程,直到它完成然后播放第二个线程。我无法弄清楚这个线程有什么问题,因为我不熟悉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();
}
}
答案 0 :(得分:-2)
线程很棘手,并且总是不可能在运行期间判断哪个线程具有优先级,因为它依赖于JVM。运行线程t1和t2的方式,不能保证t1将始终在t2之前执行,反之亦然。我建议使用wait和notify来管理线程执行。