Menu
Question Index
...

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 B C
ABC ABC ABC
ABC DEF GHI
null null null
Compilation or Runtime Error

Doubts

Problems

Topic: Other Advanced Topics In Java

Read this topic
Take test on this topic

0
Wrong
Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App