所以我正在学习Java中的线程,并重新访问了我们创建声音的课程中的一个旧课程。每当我运行程序时,我的线程上都会得到一个ArrayIndexOutOfBoundsException:2730。这是我在课堂上的代码
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();
}
}
确切的错误是
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)
警告线:88 - 蜂鸣器:89是
buffer[bufferSize++] = (byte) s;
buffer[bufferSize++] = (byte) (s >> 8); // little Endian
我明白了。 Beeper类已经创建了数组,第二个线程尝试创建一个新数组。感谢@Ken White的帮助
答案 0 :(得分:0)
我所做的只是创建一个新的蜂鸣器子类。
if (threadName.equalsIgnoreCase("Thread 2")) {
Beeper beep2 = new Beeper1();
beep2.beep(233, 800);
beep2.beep(262, 800);
beep2.beep(294, 800);
beep2.sleep(1600);
beep2.beep(233, 800);
beep2.beep(262, 800);
beep2.beep(294, 800);
beep2.beep(294, 400);
beep2.beep(294, 400);
beep2.beep(294, 400);
beep2.beep(294, 400);
beep2.beep(262, 400);
beep2.beep(262, 400);
beep2.beep(262, 400);
beep2.beep(262, 400);
beep2.beep(233, 800);
beep2.beep(262, 800);
beep2.beep(294, 800);
Thread.sleep(50);
}
感谢帮助人员