简体   繁体   中英

What is the correct way to make a thread return a value?

I'm new to Java threads and after testing to see how they work, I can't figure out how to make them do calculations and return the result the way I want.

For example, in my current program, I want my thread to query a database by calling a method that returns the data in a Vector object when I click a JButton . Then, with that vector object, I want to add each index (an array) as a row in a JTable .

What would be the correct way to accomplish this? I know I could use a setter on my JTable in the calling class but I'm sure there has to be a more "correct" way.

Yes, use a SwingWorker . This mechanism is designed for situations where you need to have a long running task run in a background thread and provide updates to the UI either when done, or while processing. Since Swing is single-threaded, this allows the UI to remain responsive .

or basic workaround by impements Runnable where output to the GUI must be wrapped into invokeLater more about in Concurrency in Swing

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM