[go: up one dir, main page]

0% found this document useful (0 votes)
110 views4 pages

Home Assignment - Week 13: 1. Reverse Goodbye

1. The document provides 6 home assignment problems involving multi-threaded programming in Java. The first problem involves creating 10 threads that print greetings and goodbyes in a specific order. The second problem involves sharing a variable between 2 threads. The third problem involves summing the values of an array using 4 threads. The fourth problem involves reading input and having the corresponding thread print a greeting. The fifth problem simulates a ping pong game between 2 threads. The sixth and optional problem involves a producer-consumer problem with string generation and processing.

Uploaded by

Cosmin Grosu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
110 views4 pages

Home Assignment - Week 13: 1. Reverse Goodbye

1. The document provides 6 home assignment problems involving multi-threaded programming in Java. The first problem involves creating 10 threads that print greetings and goodbyes in a specific order. The second problem involves sharing a variable between 2 threads. The third problem involves summing the values of an array using 4 threads. The fourth problem involves reading input and having the corresponding thread print a greeting. The fifth problem simulates a ping pong game between 2 threads. The sixth and optional problem involves a producer-consumer problem with string generation and processing.

Uploaded by

Cosmin Grosu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Home Assignment - Week 13

1. Reverse Goodbye
Write a program that creates a thread (let's call it Thread 1). Thread 1 creates another thread
(Thread 2); Thread 2 creates Thread 3, and so on, up to Thread 10.

Each thread should print "Hello from thread <num>" and then “Goodbye from thread <num>”,
but you should structure your program such that the threads print their greetings in this order:
Hello from thread 1
Hello from thread 2
...
Hello from thread 10
Goodbye from thread 10
...
Goodbye from thread 1

Note that the requirement is to actually create/run this code on multiple parallel threads! (not a
single main one).
Also, you should not use Thread.sleep() in your threads (would be too easy a solution :) and
also the program would run slower than necessary...)
Hint​: read about .join() method of Thread class...

For this exercise, try to create the threads by extending the Thread class.

Optional​: once you solve it, can you think of a second different solution for it?...

2. Shared Resource
Start 2 new threads, and find a way to share a variable between them. 
The 2 thread will have different roles: 
- one should sleep a little, then change the value of the shared variable, then end; 
- the 2nd one should wait for the change (in a loop with sleep), detect when the 
variable has changed and print a message about the change (old and new value), 
and then end; 
 
Optional​: once you have a solution, think about a 2nd different way in which you can 
share the variable between the 2 threads..
3. Parallel Array Sum
Write a program that sums the values from an array of ints using 4 threads.
- Each thread gets to sum a quarter of the array and then stores its partial result somehow
(in some kind of shared location?).
- The main thread needs to start and wait for the above threads to finish, after which it
collects the 4 partial answers, sums them and displays the final result.

For this exercise, try to create the threads by implementing the Runnable interface.

4. Interactive Multi-threaded Greeter


Create 10 new threads. They should have each a number (1..10) and run in the background
waiting.
- The main thread should start reading from user (from console) some integer numbers, in a
loop.
- if the current read number matches the number of one of the threads, then ​only that thread
should print "Hello from thread [number] (thread id: [id])" (and only once)
- if current number is -1 then ​all​ threads should write a goodbye message and then end (each
one writing "Goodbye from thread [number]").

5. Ping-Pong Threads Game


We will simulate a game of ping pong between 2 players, represented each by a thread.

Read first a number N from keyboard (between 1 and 10). This will determine the length
of the game. (how many ping-pong messages will be exchanged between players)

Then start 2 threads, T1 (‘Pinger’) and T2 (‘Ponger’):


- T2 starts in a waiting state

- T1 starts the game by sending "​Ping 1​" to T2, which sends back "​Pong 1​" …
- T1 waits for the reply, and after receiving “​Pong​ ​x”​, will send to T2 the message
“​Ping x+1​” for a new round, etc..

- the match 'ends' when message "​Pong N​" was sent -> in this case both threads
should end, and then also the main one.
Other rules:
- threads must not get out of sync: each thread must wait to receive the right
message before responding to it
- threads should sleep for a random amount of time (1000-2000ms) before
sending a message back
- threads should write messages to console when receiving and when sending any
messages (including thread role + id for clarity)

Questions:
- In what format should you send the message? Think about how you'll need to
consider both the type of the message (Ping/Pong) and the number of it. (hint:
your message doesn't need to be a single/primitive value..)
- How should you send it? Multiple ways are possible, what is the easiest/better fit
here? (shared variable, atomic object, a blocking queue?..)
- Do you need more than 1 channel / shared resource to send the messages?
(how do you send to different destinations?)

Optional: ​instead of the game starting immediately when T1 starts, change your code
so both threads start in waiting state, and game starts only when the main thread sends
a special message, “Start”, to thread T1 (which will then send “Ping1” etc..)

(Optional) 6. Producer-Consumer
Consider having a class called ​StringsGenerator​, that generates random strings using the
following algorithm:
● Generate a random integer between 3 and 13; this will be the length of the word
● Generate the string, by randomly generate each letter (in ‘a’-’z’ interval)

Write a ​StringsProcessor ​interface with the following implementations:


● StringsPrinter​, prints a string to the console
● VowelsCounter​, prints to the console the number of vowels in a word
● StringsLength​, prints to the console the length of a string
● VowelsRemover​, prints to the console the string that results from removing all vowels

Then write a ​StringsProducer ​thread that randomly generates 100 string values, and for
each of them it also chooses randomly one of the strings processing algorithms described
above, to be applied on that string later in consumer.
Finally write a ​StringsConsumer ​thread that receives the above objects (string value +
processing algorithm) and applies the algorithm to the string, and prints the result.

The communication between the two threads should be done via an ​ArrayBlockingQueue
instance. Use the ​put()​ and ​take()​ methods (and possibly ​peek()​)

Optional:
- For a cleaner end of the program:
- after generating all values, put an extra special value on the queue (a “poison”
item) which will signal to the consumer threads, when they detect it, that they
should end too
- In main thread, after starting the new threads (1producer+2consumers), wait until
all new threads completed, before ending main thread too
- Make your solution work with 2 or more consumer threads; and for clearer output, print
from the consumers also the thread id, when processing a value from queue
- questions here: how many changes did you have to make to support this? What
about having 2 producers + 3 consumers? Did you need any changes also to the
consumer code handling the “poison” value? (for all consumer threads to finish)

You might also like