Menu
Topics Index
...
`

Threads1706


If you need explanation Read this topic

If you need Answer Take test on this topic

Threads1706
What is the output of the following program?
import java.util.concurrent.atomic.*;

public class Modi {
    public static void main(String[] args) {
        new Rope("M");  new Rope("E");
        new Rope("R");  new Rope("I");
        new Rope("T");
    }
}
class Rope implements Runnable {
    String name;
    public Rope(String name) {
        this.name = name;
        new Thread(this).run();
    }
    public void run() {
        for (int i = 1; i < 2; i++) {
            System.out.print(name + " : " + Shared.ai.getAndSet(i) + " ");
        }
    }
}
class Shared {
    static AtomicInteger ai = new AtomicInteger(2);
}

A. M : 2 E : 1 R : 0 I : 0 T : 0
B. M : 2 E : 1 R : 1 I : 1 T : 1
C. M : 2 E : 2 R : 2 I : 2 T : 2
D. M : 1 E : 1 R : 1 I : 1 T : 1
E. Compilation or Runtime Error
Topic: Other Advanced Topics In Java

If you need explanation Read this topic

If you need Answer Take test on this topic

User comments below. All of them might not be correct.

ans is B.

Posted by Gopinath Manchikanti    2014-07-09 12:55:24


Ans is B. First ai value is set to 2 int the Shared class and after calling the getANdSet() method the old value is returned and the new value is set. SO for the first time 2 is returned and for remaining 1 is given as there will be only 1 iteration for i = 1

Posted by Nikhil Sulibhavi    2014-07-09 12:57:28


ans b.
atomic integer value 2 is asignd to 1st thread.
aft all threads r taks value befr the atomic value 2. take 1

Posted by Maheshwari Natarajan    2014-07-09 12:59:52


ans is B,getAndSet()  method in AtomicInteger class atomically sets to the given value and returns the old value.

Posted by Raviteja Daggupati    2014-07-09 13:07:02


Answer B.
AtomicInteger prevnts 2 thread from writing to ai at same time.
1st thread valu asignd as 2.
by calling the getandset method ai value is chngd.
tis methd retuns previous value of 2.
so it givs 1 fr othrs

Posted by NagaRaj Nataraj    2014-07-09 13:07:15


Congratulations Nikhil Sulibhavi. You are this dose winner. We will send you the link using which you can claim your recharge.

Posted by Merit Campus    2014-07-10 04:28:21


© meritcampus 2019

All Rights Reserved.

Open In App