gpt4 book ai didi

java - 从 ArrayList 恢复和挂起线程

转载 作者:行者123 更新时间:2023-12-02 07:48:14 27 4
gpt4 key购买 nike

我在使用 Java 时遇到问题。我想编写一个程序,其中有一个主类,其中有某个类(类任务)的线程数组列表,它只写一个字母和数字。 Main 对象只是从 ArrayList 中唤醒一个线程并让它做某事,而同一对象(Main)则 hibernate 另一个线程。但我在类任务中收到非法状态错误:

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

}


}

最佳答案

如果您阅读 Thread.start() 的 Javadoc你会发现它说:

It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution.

这就是非法国家的来源。

此外,您调用了 Object.wait() 但从未调用过 notification(),这让我相信您对自己在做什么知之甚少。所以我建议你拿起一本书来阅读有关 Java 中的多线程和同步的内容。这是一个很难的主题,但是一旦你掌握了它,就会非常有收获。

关于java - 从 ArrayList 恢复和挂起线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10559864/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com