Может ли кто-нибудь показать мне правильный метод в Java, чтобы прервать все запущенные потоки и возобновить их? [дубликJAVA

Программисты JAVA общаются здесь
Ответить Пред. темаСлед. тема
Anonymous
 Может ли кто-нибудь показать мне правильный метод в Java, чтобы прервать все запущенные потоки и возобновить их? [дублик

Сообщение Anonymous »

Может ли кто-нибудь показать мне правильный метод в Java, чтобы прервать все запущенные потоки и возобновить их? Мое окно пользовательского интерфейса закрывается само по себе при вызове метода Shutdown(). Я использую system.exit(), чтобы остановить программу. Как приостановить, завершить и возобновить все запущенные потоки, не закрывая окно пользовательского интерфейса.
Вот мой графический интерфейс
Изображение

Вот мой код

Код: Выделить всё

public abstract class Event implements Runnable, Serializable {
public long eventTime;
public final long delayTime;
public boolean suspended;

GreenhouseControls gc;

public Event(long delayTime) {
this.suspended = false;
this.delayTime = delayTime;
start();
}

public Event(long delayTime, GreenhouseControls gc) {
this.delayTime = delayTime;
this.suspended = false;
this.gc = gc;
start();
}

public void start() { // Allows restarting
eventTime = CustomTimeProvider.getCurrentTimeMillis() + delayTime;
}

public boolean ready() {
return CustomTimeProvider.getCurrentTimeMillis() >= eventTime;
}

public abstract void action() throws Controller.ControllerException;

public void setPaused(boolean paused) {
this.suspended = paused;
}

public void run() {
while (!suspended) {
if (this.ready()) {
System.out.println(this);
try {
CustomTimeProvider.setCurrentTime(CustomTimeProvider.getCurrentTime()); // Update current time
this.action();
this.gc.removeEvent(this);
} catch (Exception e) {
throw new RuntimeException(e);
}
return; // Added to exit the loop after executing the action
}
try {
Thread.sleep(delayTime);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}

// Method to suspend the thread
public void suspend() {
suspended = true;
}

public void resume() {
suspended = false;
}

}
public class GreenhouseControls extends Controller implements Serializable {
private transient List\ threads = new ArrayList\(); // Declaration of threads list
private transient Thread t = new Thread();
private volatile boolean isRunning = true; // Flag to control running state
private List\ events = new ArrayList\();
private static final long serialVersionUID = 1L;

public void readFile() throws ClassNotFoundException, InstantiationException,
IllegalAccessException, FileNotFoundException { {
File myObj = new File(getEventsFileTuple().getValue());

try (Scanner myReader = new Scanner(myObj)) {
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
String[] fields = data.split(",");
String[] keyValueClass = fields[0].split("=");
String[] keyValueTime = fields[1].split("=");
String classValue = keyValueClass[1];
String argValue = keyValueTime[1];
Event e;
Class cls = Class.forName("tme4." + classValue);
Constructor[] constructors = cls.getConstructors();

if (fields.length == 3) {
String[] keyValueRing = fields[2].split("=");
String ringValue = keyValueRing[1];
e = (Event) constructors[0].newInstance(Long.parseLong(argValue), this,
Long.parseLong(ringValue));
} else {
e = (Event) constructors[1].newInstance(Long.parseLong(argValue), this);
}
events.add(e); // Store reference to the event
Thread t = new Thread(e);
threads.add(t);  // Store reference to the thread
t.start();
}

} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
}

public void shutdown(String shutdownMessage, int code) throws IOException {
LocalDateTime currentTime = LocalDateTime.now();

// Create a formatter with your desired format pattern
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

// Format the current time using the formatter
String formattedTime = currentTime.format(formatter);

// Display shutdown message with current time
System.out.println("Greenhouse is shutting down at: " + formattedTime + " because: " + shutdownMessage);

setVariables("errorcode", code);

// Log to error.log
try (FileWriter errorfw = new FileWriter("error.log", true);
PrintWriter errorOut = new PrintWriter(errorfw);
FileOutputStream errorFow = new FileOutputStream("dump.out")) {

errorOut.println("Shutdown Time: " + formattedTime +
" ::: Greenhouse is shut down because: " + shutdownMessage + " with error code: " + getErrorcodeTuple().getValue() + "\n");
System.out.println("Shutdown Time: " + formattedTime + " ::: " +
"Greenhouse is shut down because: " + shutdownMessage + " with error code - " + getErrorcodeTuple().getValue());

// Serialize the GreenhouseControls object
serialize("dump.out");
} catch (IOException e) {
System.err.println("Error occurred during shutdown: " + e.getMessage());
} finally {
// Close resources in a finally block
// exit code

stopThreads();

}
}
public void stopThreads() {
// Interrupt all the threads
for (Thread t : threads) {
t.interrupt();
}
}
Метод stopThreads() не сработал. События все еще выполняются при вызове stopThreads()

Подробнее здесь: https://stackoverflow.com/questions/784 ... -threads-a
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «JAVA»