This lab works on the basics of handling threads, and their synchronisation.
Oracle Java Tutorial links
- Create and use the Thread class and the Runnable interface.
- Manage and control thread lifecycle.
- Synchronize thread access to shared data.
- Identify potential threading problems.
Multithreading is commonly used to handle multiple independent client requests in web or database servers for example. This exercise simulates a single application interacting with multiple background tasks.
The class CPUProcess.java simulates a backend task occurring - in real life it could be a database query or communicating with another server. Get the class from the link above and save it in the package threads The simulated process uses up some CPU time and then returns.
An automated test has been created for this exercise: CPUProcessTest.java.
The test class will test the execution speed on your computer. Adjust the value of CPUProcess.DIFFICULTY to have the process take about 3 seconds to run.
Write a class SlowProcessor with a main method which executes CPUProcess.run() 10 times without threading.
Write a class ThreadedProcessor with a main() method which executes CPUProcess.run() 10 times, executing each CPUProcess process in a separate thread. The ThreadedProcessor.main() method should only terminate after all the process threads have terminated. Use only the thread handling methods within Runnable and Thread to accomplish this. ThreadedProcessor should be significantly faster than SlowProcessor on most machines.
An automated test has been created for this exercise: ProcessorTest.java.
The test class will run both implementations, checks that each are working correctly, and checks the speed increase from running the processes in multiple threads.