Java Threads
Creating a Thread class:
- Just inherit from the Thread class, and override the run function
Running a thread
- Instantiate it like any other object, then call the start method
- Threads allow different processes to be run simultaneously so others can perform even while one is delayed
Delays and Interrupts
- Thread.sleep function will pause the thread for a specified number of milliseconds
- With the interrupt there, the delayed action will not be reached
- This can be useful for making a background process stop when a user interacts with the main thread
Challenge
Create 2 threads, make one thread count from 1 to 10 (with a half-second delay after each), make the other thread count by twos from 2 to 20 with a one-second delay between each number. Program the one that finishes first to end the other thread. Run them simultaneously.