Show me your love

Report a typo

Imagine you have created a class called Mouth. Its sole purpose is to say one true and correct statement.

public class Mouth {
    public void first() {
        System.out.print("I ");
    }

    public void second() {
        System.out.print("love ");
    }

    public void third() {
        System.out.print("programming");
    }
}

The same instance of Mouth will be passed to three different threads. Thread A will call first(), thread B will call second(), and thread C will call third(). Design a mechanism and modify the program to ensure that second() is executed after first(), and third() is executed after second().

The input format is space-separated letters A, B, and C, like:

input = A C B

There are three threads being fired asynchronously. The input A C B means thread A calls first(), then thread C calls third(), and lastly thread B calls second(). However, the program should still print "I love programming!", which is the correct output.

You don't know how the threads will be scheduled in the operating system, even though the numbers in the input seem to imply the ordering. The input format you see is mainly to ensure the comprehensiveness of our tests.

Sample Input 1:

A B C

Sample Output 1:

I love programming!

Sample Input 2:

A C B

Sample Output 2:

I love programming!
Write a program in Java 17
import java.util.concurrent.*;

class Mouth {
//declare your attributes here

public Mouth() {
//init your attributes here
}

// Update the method
public void first() throws InterruptedException {
System.out.print("I "); // Do not change or remove this line
}

// Update the method
public void second() throws InterruptedException {
System.out.print("love "); // Do not change or remove this line
}

// Update the method
public void third() throws InterruptedException {
System.out.print("programming!"); // Do not change or remove this line
}
}
___

Create a free account to access the full topic