我对 Java 有疑问。我想编写一个程序,其中有一个类 Main,它有一些类(类任务)的线程的 ArrayList,它只写一个字母和数字。Object Main 只是从 ArrayList 中唤醒一个线程,并让它在同一个对象(Main)休眠另一个线程时做某事。
它工作正常:0A、0B、0C、1B、1C、1A、2B、2A、2C、3B、3C、3A、4B、4C、4A、5B、5A、5C、
但只有当我评论:e.printStackTrace() e is Exception 然后我在 Main.run(Main.java:22) 的 java.lang.Object.notify(Native Method) 处得到很多 java.lang.IllegalMonitorStateException
所以通知工作错误,我应该如何正确唤醒它,请告诉我,显示,正确。请
import java.util.ArrayList;
import java.util.ArrayList;
public class Main extends Thread {
ArrayList<Thread> threads;
public Main() {
super();
threads = new ArrayList<Thread>();
}
public void run() {
for (int i = 0; i < 3; i++) {
threads.add(new Thread(new Task(i + 65)));
}
long cT = System.currentTimeMillis();
for (int i = 0; i < threads.size(); i++) {
threads.get(i).start();
}
while (System.currentTimeMillis() - cT < 10000) {
for (int i = 0; i < threads.size(); i++) {
try {
threads.get(i).notify();
// HOW TO WAKE THREAD FROM threads ArrayList
Thread.sleep(1000);
// how to put to bed the same thread ?
threads.get(i).wait();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
new Main().start();
//new Thread(new Task(65)).start();
}
}
H
public class Task implements Runnable {
int nr;
char character;
public Task(int literaASCII) {
this.nr = 0;
character = (char) (literaASCII);
}
@Override
public void run() {
while (true) {
try {
System.out.print(nr + "" + character + ", ");
nr++;
int r = (int) ((Math.random() * 500) + 500); // <500ms,1000ms)
Thread.sleep(r);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}