我有一個Java的問題。我想寫一個程序,其中有Class 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是異常 然後 我在java.lang.Object.notify(本機方法) 在Main.run(Main.java得到很多 java.lang.IllegalMonitorStateException :22)
所以通知工作不正確,我該如何正確地喚醒它,請告訴我,顯示,正確。請
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
}
}
以上是實用上完全錯誤的領導。你究竟在做什麼?有一個單獨的任務線程工作,而其餘的睡眠?並讓主線程按順序使任務線程發生? – alphazero