简体   繁体   中英

running two objects at once with threads?

I am trying to run an object that makes a sine wave over itself using threads. When I try to play the object over one another with threads it plays the first thread waits till it finishes then plays the second thread. I cannot figure out what is wrong with this threading because I am new to threads in java. Thank you for your help and response!

Here is the code:

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();
    }



}

Threads are tricky and it is not always possible to tell which thread will have priority during the run as it is JVM dependent. The way you are running the threads t1 and t2 , there is no guarantee that t1 will always execute before t2 and vice versa. I suggest using wait and notify to manage the thread execution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM