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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.