Question
Using multithreading you are able to have multiple threads (for our purposes, we can also think of them as processes as well). Read the short
Using multithreading you are able to have multiple threads (for our purposes, we can also think of them as processes as well). Read the short primer posted on Piazza about multithreading in Java and review the examples covered in the discussion section. a. Write a Java program that will spawn and run concurrently five threads of the same code. The code that each thread will follow should consist of a loop that executes five times. Each iteration of the loop should start by having the thread print the first of the five lines below (using a "print" statement), then sleep for some random amount of time (say between 0 and 20 msec), then print the second line, then sleep again, etc. until all five lines below are printed out. "Thread i is starting iteration k" "We hold these truths to be self-evident, that all men are created equal," "that they are endowed by their Creator with certain unalienable Rights," "that among these are Life, Liberty and the pursuit of Happiness." "Thread i is done with iteration k" Run your code and show that the output of the five threads will be interleaved (making the output incomprehensible). b. To make the above work, you will need to use a critical section so that the five print statements in a single iteration are all inside that critical section. Use the bakery algorithm to ensure that behavior and show the resulting (now comprehensible) output. c. Repeat part (b) but using java semaphores instead.
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started