Java Multi-Threading synchronization interview question


The multi-threading synchronization questions always concentrate on a few keywords: wait, notify, notifyAll, synchronized, volatile.
The following question is the hardest, I ever met. The thread t1 should print integer number from 1–52, the thread t2 should print character from A-Z, the question is how to let the final result to be 12A34B56C… by implement Printer class.
(The Printer class is already finished by the way)

public class Main {

    public static void main(String[] args) {
        System.out.println("Hello World!");

        Printer p = new Printer();
        Thread t1 = new NumberPrinter(p);
        Thread t2 = new LetterPrinter(p);
        t1.start();
        t2.start();

    }
}

public class LetterPrinter extends Thread {

    private Printer p;
    public LetterPrinter(Printer p){this.p = p;}

    public void run(){
        for(char c='A'; c<='Z'; c++){
            p.print(c);
        }
    }
}

public class NumberPrinter extends Thread {
    private Printer p;
    public NumberPrinter(Printer p){this.p = p;}

    public void run(){
        for(int i = 1; i<=52; i++){
            p.print(i);
        }
    }

}

public class Printer {

    private volatile int m = 1;

    public synchronized void print(int i ) {

        while(m % 3 == 0) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println(i);
        m++;
        notifyAll();
    }

    public synchronized void print(char i) {

        while (m % 3 != 0) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println(i);
        m++;
        notifyAll();

    }

}



Comments

Popular posts from this blog

Bluedroid stack in android

How to setup a NAT server?

Network programming in elisp