Menu
Topics Index
...
`

Threads1941


If you need explanation Read this topic

If you need Answer Take test on this topic

Threads1941
What will be the output of the following program?
public class NewQuestion {
    public static void main(String[] args) {
        new VolatileTest("Merit").run();
        new VolatileTest("Campus").run();
    }
}
class VolatileTest extends Thread {
    private volatile int testValue;
    private volatile boolean ready;
    public VolatileTest(String str) {
        super(str);
    }
    public void run() {
        for (int i = 0; i < 2; i++) {
            try {
                if (getName().equals("Merit")) {
                    ready = true;
                    testValue = i;
                    System.out.println(getName() + ", " + ready + ", " + testValue);
                }
                if (getName().equals("Campus")) {
                    System.out.println(getName() + ", " + ready + ", " + testValue);
                }
                Thread.sleep(1000);
            } catch (InterruptedException exception) {
                exception.printStackTrace();
            }
        }
    }
}

A. Merit, true, 0
Campus, false, 0
Merit, true, 1
Campus, false, 0
B. Merit, true, 0
Merit, true, 1
Campus, false, 0
Campus, false, 0
C. Merit, true, 0
Campus, false, 0
Campus, false, 0
Merit, true, 1
D. Some other output
E. Output can not be determined
F. Compilation Error or Runtime Error
Topic: What is Multitasking and Multithreading?

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 must be B as the first run method runs, the 1st if gets satisfied twice.. so it prints
merit true 0
merit true 1
and for the second run it prints
campus false 0
campus false 0 bcoz second if gets satisfied, testvalue remains 0 in dis case, ready remains false as default values for cls variables

Posted by Pramod Jain    2013-11-15 12:40:56


Answer is B...as volatile / multithreading is not applicable because you are invoking threadobject.run() method rather using threadobject.start() method
In order to make threads to become multithreaded we should always start using threadobject.start() method
volatile objects can be modified dynamically when multithreading is happening and each time volatile variables values is read from variable's storage location rather previously read value

Posted by Jayachandra Gupta    2013-11-15 13:19:48


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

Posted by Merit Campus    2013-11-18 04:08:33


thank u mc :) got rc :) :)

Posted by Pramod Jain    2013-12-03 04:35:42


© meritcampus 2019

All Rights Reserved.

Open In App