我对 Java 有疑问。我想编写一个程序,其中有一个类 Main,它有一些类(类任务)的线程数组列表,它只写一个字母和数字。Object Main 只是从 ArrayList 中唤醒一个线程,并让它在同一个对象(Main)休眠另一个线程时做某事。但是我在类任务中得到了非法状态的错误:
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
}
}