Simple threads
Study the following class:
// Subclass extends Thread class public class PrintNameThread extends Thread { PrintNameThread(String name) { super(name); } // Override the run() method of the Thread class. // This method gets executed when start() method // is invoked. public void run() { System.out.println("run() method of the " + this.getName() + " thread is called" ); } }
Then consider this class:
public class ExtendThreadClassTest0 { public static void main(String args[]) { // Create object instance of a class that is subclass of Thread class System.out.println("Creating PrintNameThread object instance.."); PrintNameThread pnt1 = new PrintNameThread("A"); // Start the thread by invoking start() method System.out.println("Calling start() method of " + pnt1.getName() + " thread"); pnt1.start(); } }
What output do you expect? Implement and run the program in your IDE. Is the output as expected?
Threads returning values
Write a program which starts two threads and passes a name as a String two each of them (two different names). You can either hardcode those names or ask the user for them. Each thread should return "Hello <name>" to the main thread. The main thread should print out those two messages once both threads have finished. How many classes do you need for this? If you want, put a sleep() into the thread to see the main thread waiting for the threads to finish.
Threads doing real work
We want to find the number in a range of positive numbers which has the maximum number of divisors. A divisor is a number which divides another number with remainder 0. For example, 9 has two divisors, namely 3 and 1, whereas 8 has three, namely 1,2, and 4 (if the 1 is included or not does not matter for the maximum). Using the int data type should be enough for this exercise.
As a first step, write a program which finds the divisors for a number.
Then extend this to find the maximum number of divisors for a range in a sequential fashion. Try this out for e.g. the range from 1 to 1000 and 1 to 100,000 and 1 to 10,000,000. Record how long it takes for 1 to 10,000,000.
Finally, implement a concurrent version. For this, write a thread which finds the maximum for a range. Then write a program which uses this thread to calculate the maximum for the range of 1 to 10,000,000. Try out what happens if you divide the range in different number of chunks. You can start with 2 and increase it. Do you get a speedup compared to the serial version?
Is there a need to use synchronized or volatile in this exercise?