✅ The verified answer to this question is available below. Our community-reviewed solutions help you understand the material better.
The following code contains the classes Hobbit, Ring, and the creation and start of three Hobbit threads in class Main / main().
class Ring { String owner = "Who knows";} class Hobbit extends Thread { String name; Ring ring; Hobbit (String name, Ring ring) { this.name = name; this.ring = ring; } @Override public void run() { ring.owner = name; System.out.println(name + " says: the precious is mine, " + ring.owner); }}// Class Main public static void main(String[] args) { Ring ring = new Ring(); Hobbit gollum; Hobbit bilbo; Hobbit frodo; gollum = new Hobbit("Gollum",ring); bilbo = new Hobbit("Bilbo Baggins",ring); frodo = new Hobbit("Frodo Baggins",ring); gollum.start(); bilbo.start(); frodo.start(); }
Which of the following statements assure mutual exclusion and thus, lead to the expected, thread-safe output?
a) Changing run() in class Hobbit to:
@Overridesynchronized public void run() { ring.owner = name; System.out.println(name + " says: the precious is mine, " + ring.owner);}
b) Changing run() in class Hobbit to:
@Overridepublic void run() { synchronized(ring) { ring.owner = name; System.out.println(name + " says: the precious is mine, " + ring.owner); }}
c) Changing the creation of the threads in Class Main (main()) as follows:
synchronized (ring) { gollum = new Hobbit("Gollum",ring); bilbo = new Hobbit("Bilbo Baggins",ring); frodo = new Hobbit("Frodo Baggins",ring);}
d) Changing the starting of the threads in main() as follows:
synchronized (ring) { gollum.start(); bilbo.start(); frodo.start();}