Share
Explore BrainMass

Java program to print a string in distributed manner

Design a Java "Hello World" program that should mimic distributed processing of printing the string "Hello World!" on display.

For doing this the main() method should just create 5 threads and store references to them in an array of threads, which will be passed to each thread for communication purposes. Then the main() method should start all threads, wait for their completion and exit. It must not control the threads in any way or send any other information to them.

Each thread will compete for the display access and once it is granted, the thread prints out only one character of the string (namely the next one in order) and then starts to compete for the display access again for printing the next character. If all characters of the string are printed, the thread exits. This way each of the threads will execute the same algorithm and print just a few string characters.

Printing a string character can be considered as a critical part of the thread code. For this, implement a mechanism providing mutual exclusion, but without using any synchronization approaches (semaphores, locks, etc.). Each of the threads should be able to communicate with other threads by sending messages to them. The communication must be purely distributed in the sense that no other shared object is available to threads besides of the Thread array workers.

Solution Preview

Please find attached 364998-DistributedHello.java that you should rename as DistributedHello.java before compiling and running.

The constructor of the thread class Worker (that extends Java API class Thread) takes just two parameters, namely the array of thread objects created by the main method and the string to print.

In order for threads to communicate, the class Worker provides a public method putMessage, which accepts messages from other threads in the format WorkerMessage and puts them into an ArrayList. Therefore, before printing a character each thread sends messages to all other threads letting them know that it intends to print string character at index i (i=0 at the beginning) along with a timestamp (taken from the system clock). Then the thread waits for responses ...

Solution Summary

The constructor of the thread class Worker (that extends Java API class Thread) takes just two parameters, namely the array of thread objects created by the main method and the string to print. In order for threads to communicate, the class Worker provides a public method putMessage, which accepts messages from other threads in the format WorkerMessage and puts them into an ArrayList. Solution also suggests few experimentations with the code so that you can see different characters being printed by different threads.

$2.19