Menu
Topics Index
...
`

Classes Implementing Runnable Interface


If you need explanation Read this topic

If you need Answer Take test on this topic

Classes Implementing Runnable Interface
What is the output of the following program?
import java.util.concurrent.*;

public class Exchange {
    public static void main(String[] args) {
        Exchanger<String> exgr = new Exchanger<String>();
        new MyClassB(exgr);
        new MyClassA(exgr);
    }
}
class MyClassA implements Runnable {
    Exchanger<String> ex;
    String str;
    public MyClassA(Exchanger<String> ex) {
        this.ex = ex;
        str = new String();
        new Thread(this).start();
    }
    public void run() {
        char c = 'A';
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++)
                str += c++;
            try {
                str = ex.exchange(str);
            } catch (InterruptedException e) {  }
        }
    }
}
class MyClassB implements Runnable {
    Exchanger<String> ex;
    String str;
    public MyClassB(Exchanger<String> ex) {
        this.ex = ex;
        new Thread(this).start();
    }
    public void run() {
        for (int i = 0; i < 3; i++) {
            try {
                str = ex.exchange(new String());
                System.out.print(str + " ");
            } catch (InterruptedException e) {   }
        }
    }
}

A. A B C
B. ABC ABC ABC
C. ABC DEF GHI
D. null null null
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.

Answer is B at every iteration of 'i' is MyclassA class we get ABC which is exchanged with thread of MyClassB .

Posted by Ashok Kumar Paritala    2014-08-15 12:40:53


ans c.
inner for loop performs increment operation
so for i=0 ABC exchanged
i=1 DEF
i=2 GHI
thes string of thread executed.

Posted by Maheshwari Natarajan    2014-08-15 13:08:06


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

Posted by Merit Campus    2014-08-18 05:13:43


© meritcampus 2019

All Rights Reserved.

Open In App