Saturday, October 27, 2012

Print alternate string in Java by 2 threads

I kept getting asked this question in interviews so here it is for the benefit of others


package com.threads;

import java.util.logging.Level;
import java.util.logging.Logger;


public class Master {
    private static Object lock = new Object();
    public static void main(String[] args) {
        new Slave1(lock).start();
        new Slave2(lock).start();
    }
   
}

class Slave1 extends Thread {
   private Object lock;
   Slave1(Object lock){
       this.lock=lock;
   }
   @Override
   public  void run(){
     while(true){
       synchronized(lock){
            System.out.println("Slave1");
            lock.notify();
            try {
                lock.wait();
            } catch (InterruptedException ex) {
                Logger.getLogger(Slave1.class.getName()).log(Level.SEVERE, null, ex);
               
            }
           
        }
     }
    }
}


class Slave2 extends Thread {
   private Object lock;
   Slave2(Object lock){
       this.lock=lock;
   }
   @Override
   public  void run(){
       while(true){
        synchronized(lock){
            System.out.println("Slave2");
           
               
                lock.notify();
                try {
                    lock.wait();
                } catch (InterruptedException ex) {
                    Logger.getLogger(Slave2.class.getName()).log(Level.SEVERE, null, ex);
                }
           
        }
       }
    }
}

Ran this program and then redirected input to slave.log
Ran the following check to verify it is working.
 awk '^C%2 {print > "newfile"}' slave.log
grep -i slave1 newfile

I got no lines containing slave1 hence it works.

On doing some more research on the internet i found the following link ordered multi-threading in java .
This made me think that the above situation should not be present in any good design as this removes the parallelism for which threads are being used in the first place.

No comments: