So I am learning threads in Java in and I revisited one of our old lessons in class where we created sounds. Whenever I run the program I get a ArrayIndexOutOfBoundsException: 2730 on my threads. This is the code I have in the class
public class ThreadA implements Runnable {
private Thread t;
private String threadName;
public ThreadA(String name) {
threadName = name;
System.out.println("Creating " + threadName);
}
public void run() {
try {
if(threadName.equalsIgnoreCase("Thread 1")){
for(int i = 0; i < 2; i++) {
Beeper.beep(200,800) //this is a call to the Beeper Class, its useless for this examples
}
}
if(threadName.equalsIgnoreCase("Thread 2")){
for(int i = 0; i < 2; i++) {
Beeper.beep(233, 800); //line 37, where the error is
}
}
catch (InterruptedException e){
System.out.println("Thread " + threadName + " interrupted");
}
System.out.println("Thread " + threadName + " exiting");
}
public void start(){
System.out.println("Starting " + threadName);
if(t == null){
t = new Thread(this, threadName);
t.start();
}
}
The exact error is
Exception in thread "Thread 2" java.lang.ArrayIndexOutOfBoundsException: 2730
at Beeper.play(Beeper.java:88)
at Beeper.play(Beeper.java:104)
at Beeper.beep(Beeper.java:275)
at ThreadA.run(ThreadA.java:37)
at java.base/java.lang.Thread.run(Thread.java:844)
The line Beeper:88 - Beeper:89 is
buffer[bufferSize++] = (byte) s;
buffer[bufferSize++] = (byte) (s >> 8); // little Endian
I figured it out. The Beeper class already created the array and the second thread tried to create a new array. Thanks for the help @Ken White