logo

Crowdly

The following code contains the classes Hobbit, Ring, and the creation and start...

✅ Перевірена відповідь на це питання доступна нижче. Наші рішення, перевірені спільнотою, допомагають краще зрозуміти матеріал.

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 lead to consistent (name is equal to ring.owner), thread-safe output?

 

a) 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);

}

b) Changing the starting of the threads in main() as follows:

synchronized (ring) {

   gollum.start();

   bilbo.start();

   frodo.start();

}

c) Changing run() in class Hobbit to:

@Override

synchronized public void run() {

ring.owner = name;

   System.out.println(name + " says: the precious is mine, " + ring.owner);

}

d) Changing run() in class Hobbit to:

@Override

public void run() {

synchronized(ring) {

ring.owner = name;

    System.out.println(name + " says: the precious is mine, " + ring.owner);

}

}
Більше питань подібних до цього

Хочете миттєвий доступ до всіх перевірених відповідей на moodle.jku.at?

Отримайте необмежений доступ до відповідей на екзаменаційні питання - встановіть розширення Crowdly зараз!