Receive and send messages using Java threads

I want to create a thread that starts, computes something with the data that I give it, and returns multiple values ​​or an object. This thread is part of the Swing GUI.

My question is: how can I create a method that starts when a stream is created and returns an object (or is it all I want it to return)?

My code is:

private void nextTurn () { // do something if (turn == white) { try { Engine e = new Engine(); // Engine is implemented by runnable e.start(); Move m = e.getBestMove (board); // thread should work, next code should be excecuted immediately } catch (Exception e) {} } // end of Main class } 

This is the first time I've been working with Threads, and I know that you should avoid them if possible, but this time I need this GUI. The information on the Oracle website on Threads did not help me. I can make a program with multiple threads that runs indefinitely, but I cannot get it to work with functions.

+1
source share
2 answers

Since this is with the Swing GUI, consider using a SwingWorker object that creates a background thread (all code is executed in the doInBackground method) and then can return the final result and / or intermediate results. Information on how to use it is well described in textbooks:

Concurrency in Swing

SwingWorkers has support for changing properties, and thus allows listeners to observe their state (like SwingWorker.StateValue) using the PropertyChangeListener. This is one of the ways that your program can determine that the thread has completed its processing, get the return result, and go from there.

In an unrelated note, this is not in your production code, is it ?:

 catch (Exception e) {} 

If this is the case, you will most likely want to fix it, because ignored exceptions can bite you in the tail for a long time.

eg.

  if (turn == white) { try { final SwingWorker<Move, Void> mySwingWorker = new SwingWorker<Move, Void>() { @Override protected Move doInBackground() throws Exception { Engine e = new Engine(); // Engine is implemented by runnable e.start(); Move m = e.getBestMove(board); return m; } }; mySwingWorker.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { if (StateValue.DONE == mySwingWorker.getState()) { try { Move m = mySwingWorker.get(); // TODO: insert code to run on the EDT after move determined } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } } }); mySwingWorker.execute(); } catch (Exception e) { e.printStackTrace(); } } 
+3
source

I suggest you use ExecutorService. It allows you to create a thread pool, you can transfer tasks to it and get results later.

http://download.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html

+3
source

Source: https://habr.com/ru/post/896862/


All Articles