Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

3. Java Thread (50 points): Answer questions for the given Worker.java and ThreadExample.java. - What is the name of the class implementing the runnable interface?

3. Java Thread (50 points): Answer questions for the given Worker.java and ThreadExample.java.

- What is the name of the class implementing the runnable interface? What is the

name of the instance field of this class? (10 points)

- In which line an object of the class mentioned previous problem is created? (5

points)

- What does the join method do? (5 points)

- Give an example of output of this code (10 points)

- Are there only one possible output this code? If yes, explain why. If not, give

another possible output (10 points)

- Use your own language, describe the purpose of the code (10 points)

Worker.java

1 public class Worker implements Runnable {

2

3 private String name;

4

5 public Worker(String name) {

6 this.name = name;

7 }

8

9 public void run() {

10

11 System.out.printf("Worker %s starts. %n", name);

12 try {

13 doWork();

14 } catch (InterruptedException e) {

15 e.printStackTrace();

16 }

17

18 System.out.printf("Worker %s ends.%n", name);

19 }

20

21 private void doWork() throws InterruptedException {

22 int sleeptime = (int) (5 * Math.random());

23 Thread.sleep(sleeptime * 1000);

24 }

25

26 }

ThreadExample.java

1 public class ThreadExample {

2 3 public static void main(String[] args){

4 Thread worker1 = new Thread(new Worker("Alice"));

5 Thread worker2 = new Thread(new Worker("Bob"));

6

7 System.out.println("Start worker threads");

8 worker1.start();

9 worker2.start();

10

11 try{

12 worker1.join();

13 } catch (InterruptedException e) {

14 e.printStackTrace();

15 }

16

17 try {

18 worker2.join();

19 } catch (InterruptedException e) {

20 e.printStackTrace();

21 }

22 }

23 }

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Students also viewed these Databases questions