Как я могу убедиться, что мой Java-код является потокобезопасным?JAVA

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

Сообщение Anonymous »

Я пытаюсь использовать SwingWorkers в своем приложении (написанном на Java), где я собираю некоторые данные из API и отображаю их в графическом интерфейсе приложения. Имейте в виду, что я очень не уверен в том, что касается потоков, это концепция, которую мне трудно уловить и понять.
Я предоставлю метод, для которого запускается поток.< /p>

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

    private void initialThread() {
dataUpdateTimer = new Timer(60 * 60 * 1000, new ActionListener() { // Update every hour

@Override
public void actionPerformed(ActionEvent e) {
rg.getLoadingMsg(); // Display the JOptionPane message
if (cachedChannelData != null) { //If the cached data is not null
cachedChannelData.clear(); //Clear the cached data to make new cache
}
rg.clearChannelTable(); //Clear the table displaying the channels (GUI)
rg.clearGui(); //Clear the rest of the GUI
SwingWorker sw = new SwingWorker() {
@Override
protected Void doInBackground() throws Exception {
cachedChannelData = cm.loadChannels(); //Get the channels (data retrieved from API)
publish(cachedChannelData); //Send the data that's been collected
return null; // Ensure doInBackground returns null as specified by its return type
}

@Override
protected void process(List chunks) {

Map result = chunks.get(chunks.size() - 1);
for (Map.Entry channelEntry : result.entrySet()) { //For every channel data retrieved from the API, do the following

String cname = cm.getChannelName(channelEntry.getKey()); //Get the channel's name
rg.displayChannels(cname, channelEntry.getKey()); //Add that channel to the table to display it
Map programs = channelEntry.getValue(); //List of programs in that channel retrieved from the API
if(programs != null)
{ //If there are programs in the channel, hence programs != null
for (Map.Entry programEntry : programs.entrySet()) { //For every program in the channel
programClass program = programEntry.getValue(); //Get a variable containing info about that program
String description = program.getDescription(); // Get the description from the program
JLabel image = program.getDisplayImage(); // Get the image JLabel from the program
String start = program.getStart(); //Get the start time of the program
String end = program.getEnd(); //Get the end time of the program
String name = program.getName(); //Get the name of the program

// Assuming you have a method to display each program's description and image individually
rg.displayPrograms(description, image, name, start, end); // Display the programs
}
rg.clearGui(); //Clear the GUI of it's all old displayed data
}

}
}
};
sw.execute();
}
});

dataUpdateTimer.setInitialDelay(0); // Start timer immediately
dataUpdateTimer.start();
}
Вот порядок, в котором я хочу, чтобы мое приложение запускалось:

[*]Отображение сообщения (JOptionPane) >
[*]Очистить графический интерфейс
[*]Собрать данные
[*]Отобразить данные на экране
< /ол>

Подробнее здесь: https://stackoverflow.com/questions/787 ... hread-safe
Ответить

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

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

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

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

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