Детали реализации: я работаю над школьным проектом, в котором мне нужно имитировать некоторые очереди. Через случайные промежутки времени должны генерироваться клиенты, клиент выбирает одну очередь (у меня может быть несколько очередей) для входа и добавляется в эту структуру данных очереди. У каждой очереди есть свой оператор, который удаляет клиентов из очереди, к которой она присоединена.
Проблема: Генератор клиентов запускается в отдельном потоке. Графическое представление очереди представляет собой ArrayList из JButtons, отображаемый на панели GridLayout только с 1 столбцом. Когда я пытаюсь добавить клиент (JButton) на панель, я хочу использовать SwingWorker publish() для публикации нового JButton, который будет добавлен в список. Однако, после многих головных болей и System.out.println, чтобы выяснить, что происходит, я заметил, что System.out.println() в методе process() вызывается только после завершения метода doBackground().
Код здесь:
//run method of the ClientGenerator thread
public void run()
{
System.out.println("Into thread Generator");
SwingWorker<Void,JButton> worker=new SwingWorker<Void, JButton>()
{
int sleepTime;
@Override
protected Void doInBackground() throws Exception
{
while(checkTime())
{
try
{
sleepTime=minInterval+r.nextInt(maxInterval - minInterval);
System.out.println("Sleeping - "+sleepTime+" milis");
Thread.sleep(sleepTime);
System.out.println("Woke up,"+sleepTime+" milis elapsed");
} catch (InterruptedException e)
{
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
System.out.println("Generating client...");
newClient=new Client(clientMinService,clientMaxService,log);
System.out.println("Locking lock...");
operationsOnTheQueueLock.lock();
selectedQueueOperator=selectQueueOperator();
System.out.println("Adding new client to queue...");
selectedQueueOperator.getQueue().enqueue(newClient);
System.out.println("Publishing new JButton...");
publish(new JButton("C"+selectedQueueOperator.getClientIndicator()));
//}
// else
// {
// queueHolder.add(selectedQueueOperator.getQueueClients().get(0);
// }
System.out.println("Unlocking lock...");
operationsOnTheQueueLock.unlock();
System.out.println("Lock unlocked! Should enter while again and sleep");
}
return null;
}
@Override
public void process(List<JButton> chunks)
{
newClientButton=chunks.get(chunks.size()-1);
System.out.println("Process runs.Jbutton index="+newClientButton.getText());
newClientButton.setFont(new Font("Arial", Font.PLAIN, 10));
newClientButton.setBackground(Color.lightGray);
newClientButton.setVisible(true);
newClientButton.setEnabled(false);
clients=selectedQueueOperator.getQueueClients();
clients.add(newClientButton);
selectedQueueOperator.setQueueClients(clients);
// if(selectedQueueOperator.getQueueClients().size()>0)
// {
queueHolder=selectedQueueOperator.getQueueHolder();
queueHolder.add(clients.get(clients.size()-1));
selectedQueueOperator.setQueueHolder(queueHolder);
}
// return null; //To change body of implemented methods use File | Settings | File Templates.
};
worker.execute();
try {
worker.get();
} catch (InterruptedException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (ExecutionException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
выход:
Sleeping - 1260 milis
Woke up,1260 milis elapsed
Generating client...
Locking lock...
Adding new client to queue...
Publishing new JButton... ///here I should see "Process runs.Jbutton index=C0"
Unlocking lock...
Lock unlocked! Should enter while again and sleep
Sleeping - 1901 milis
Woke up,1901 milis elapsed
Generating client...
Locking lock...
Adding new client to queue...
Publishing new JButton...///here I should see "Process runs.Jbutton index=C1
Unlocking lock...
Lock unlocked! Should enter while again and sleep
Process runs.Jbutton index=C0 //instead, Process runs only in the end.
Это просто базовый пример для 2 итераций. Клиенты должны генерироваться только время от времени, поэтому в начале я сплю поток на определенное время. Затем я создаю клиентский объект, затем я хочу создать и добавить кнопку в свой компонент JPanel в методе process().
Эта последняя часть, очевидно, не происходит. Любые идеи, почему? Мне нечего попробовать, что касается SwingWorker...
Заранее спасибо!
Позднее редактирование: «замок» определяется как:
Lock lock = new ReentrantLock();
и передается как параметр из класса, который управлял моим классом ClientsGenerator(this), и моим классом, который удаляет клиентов из очереди. Он используется для их синхронизации при выполнении операций над дисплеем ArrayList&.