我遇到了Java問題。 我想編寫一個程序,其中有一個Class的Main類,它有一些類(線程任務)的線程的ArrayList,它只是寫一個字母和數字。 Object Main只是從ArrayList中喚醒一個線程,讓它做一些事情,而同一個對象(Main)睡眠另一個線程。 但我得到非法狀態的錯誤類任務:恢復和暫停ArrayList中的線程
while(suspended){
wait();
System.out.println(character);
}
整個代碼
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 < 1; 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++){
threads.get(i).start();
try {
Thread.sleep(1000);
} catch (Exception e) {e.printStackTrace();
}
threads.get(i).stop();;
}
}
}
public static void main(String[] args) {
// new Main().start();
new Thread(new Task(65)).start();
}
}
public class Task implements Runnable {
int nr;
char character;
boolean suspended, resumed, stopped;
public Task(int literaASCII) {
this.nr = 0;
character = (char) (literaASCII);
suspended = true;
resumed = true;
stopped = false;
}
@Override
public void run() {
while(true){
try{
while(suspended){
wait();
System.out.println(character);
}
if(resumed){
System.out.println("(Wznawiam watek litera: "+character+")");
resumed = false;
}
System.out.print(nr+""+character+", ");
nr++;
int r = (int)((Math.random()*500) + 500);
Thread.sleep(r);
}catch(Exception e){e.printStackTrace();}
}
}
synchronized public void suspend(){
suspended = true;
resumed = false; //chyba zbedne
}
synchronized public void resume(){
suspended = false;
resumed = true;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
謝謝,現在我糾正了它,但它看起來像那樣 – Yoda