Performing Tasks in a Worker Thread
In the next example, the user enters a number n and the program gets the nth Fibonacci number, which we calculate using a recursive algorithm. The algorithm is time consuming for large values, so we use a SwingWorker
object to perform the calculation in a worker thread. The GUI also allows the user to get the next Fibonacci number in the sequence with each click of a button, beginning with fibonacci(1)
. This short calculation is performed directly in the event dispatch thread. The program is capable of producing up to the 92nd Fibonacci number—subsequent values are outside the range that can be represented by a long
. You can use class BigInteger
to represent arbitrarily large integer values.
Class BackgroundCalculator ...
Get Android™ How to Program, Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.