Goldman Sachs Interview Question for SDE-2s


Country: United States
Interview Type: In-Person




Comment hidden because of low score. Click to expand.
1
of 1 vote

public class One {
	static String name = "oneTwo";
	static int t = 1, limit = 6;
	static volatile boolean flag = true;

	static class MyThread extends Thread {
		Semaphore sem;
		String threadName;

		public MyThread(Semaphore sem, String threadName) {
			this.sem = sem;
			this.threadName = threadName;
		}

		public void run() {
			try {
				while (flag) {
					sem.acquire();
					if (t == 7)
						break;
					if (threadName.equalsIgnoreCase("one")
							&& threadName.equals(name.substring(0, 3))) {
						System.out.print(0);
						name = name.substring(3);

					} else if (threadName.equalsIgnoreCase("two")
							&& name.equalsIgnoreCase("two")) {
						System.out.print(t);
						t++;
						name = "oneThree";
					} else if (threadName.equalsIgnoreCase("three")
							&& name.equalsIgnoreCase("three")) {
						System.out.print(t);
						t++;
						name = "oneTwo";
					}
					sem.release();
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

		}

	}
	public static void main(String[] args) {
		Semaphore sem = new Semaphore(1);
		MyThread one = new MyThread(sem, "one");
		MyThread two = new MyThread(sem, "two");
		MyThread three = new MyThread(sem, "three");
		one.start();
		two.start();
		three.start();
	}}

- Faisal September 11, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

// Globals are terribly bad...
// use closure instead
$state = 0 
$even = true 

def exit(){ $state >= 12  }

def func_0(){  
    while( !exit() ){ 
      #atomic{
        if ( 2 /? $state ){
          printf(0)
          $state += 1
          $even = !$even
        }
     } 
  } 
}

def func_even(){ 
   n = 0 
    while( !exit() ){ 
      #atomic{
        if ( $state % 2 == 1 && $even ){
          n += 2 
          printf(n)
          $state += 1
        }
     } 
  } 
}

def func_odd(){ 
   n = -1 
    while( !exit() ){ 
      #atomic{
        if ( $state % 2 == 1 && !$even ){
          n += 2 
          printf(n)
          $state += 1
        }
     } 
  } 
}

threads = [ thread() as { func_0() } , thread() as { func_even() } , thread() as { func_odd() } ]
while ( exists( threads ) where { $.o.alive } );
println()

- NoOne September 04, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

I tried using a shared variable in class to signel the threads.

package com.refresher.problems;

public class MultipleThreadsTogether {

    protected int threadSequence = 0;

    public static void main(String[] args) {
        MultipleThreadsTogether mtt = new MultipleThreadsTogether();
        mtt.printSequenceWithThreads();
    }

    public void printSequenceWithThreads() {

        Runnable r1 = new Runnable() {
            @Override
            public void run() {
                try {
                    int i=1;
                    for(i=1; i<=10; ) {
                        if(threadSequence == 0) {
                            System.out.print(" " + 0);
                            if(i%2 == 0) {
                                threadSequence = 2;
                            } else {
                                threadSequence = 1;
                            }
                            i++;
                        }
                        Thread.sleep(100);
                    }
                } catch(InterruptedException ex) {
                    ex.printStackTrace();
                }
            }
        };


        Runnable r2 = new Runnable(){
            @Override
            public void run() {
                try {
                    int i = 1;
                    for (i = 1; i <= (10 * 2);) {
                        if(threadSequence == 1) {
                            System.out.print(" " + i);
                            threadSequence = 0;
                            i = i + 2;
                        }
                        Thread.sleep(100);
                    }
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
            }
        };

        Runnable r3 = new Runnable() {
            @Override
            public void run() {
                try {
                    int i = 2;
                    for (i = 2; i <= (10 * 2); ) {
                        if(threadSequence == 2) {
                            System.out.print(" " + i);
                            threadSequence = 0;
                            i = i + 2;
                        }
                        Thread.sleep(100);
                    }
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
            }
        };

        Thread t1 = new Thread(r1);
        Thread t2 = new Thread(r2);
        Thread t3 = new Thread(r3);

        t1.start();
        t2.start();
        t3.start();
    }

}

- Mahesh Kulkarni September 06, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

@Mahesh - I am not sure if the interviewer will be mighty pleased with this solution. I guess what they want three run () methods that behave between themselves using some synchronization mechanism ( and they should be able to go as fast as possible with no deadlocks). Using some kind of global state (as you did ) is also a solution - but surely not what they are looking for. Thanks

- Makarand September 08, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

This is the solution I would come up with. Language C#.

internal class MultithreadedNumbers
    {
        private int CurrentPrint;
        private object Locker;
        private bool ReadyForZero;

        private enum NumberType
        {
            Odd, Even, Zero
        }

        internal MultithreadedNumbers()
        {
            CurrentPrint = 1;
            Locker = new object();
            ReadyForZero = true;
        }

        internal void Start(int max)
        {
            if(max < 1)
            {
                return;
            }

            Thread mod0 = new Thread(() => { ThreadMethod(max, NumberType.Zero); });
            Thread mod1 = new Thread(() => { ThreadMethod(max, NumberType.Odd); });
            Thread mod2 = new Thread(() => { ThreadMethod(max, NumberType.Even); });

            mod0.Start();
            mod1.Start();
            mod2.Start();

            // Determine if odd or even is called last and join that thread.
            if (max % 2 == 0)
            {
                mod2.Join();
            }
            else
            {
                mod1.Join();
            }
        }

        private void ThreadMethod(int max, NumberType numType)
        {
            while (Printing(max))
            {
                // Lock the locker to prevent race conditions.
                lock (Locker)
                {
                    switch (numType)
                    {
                        case NumberType.Zero:
                            if (Printing(max))
                            {
                                PrintZeros();
                            }
                            break;
                        case NumberType.Even:
                            PrintEvens();
                            break;
                        case NumberType.Odd:
                            PrintOdds();
                            break;
                    }
                }
            }
        }

        private bool Printing(int max)
        {
            return CurrentPrint <= max;
        }

        private void PrintZeros()
        {
            if (ReadyForZero)
            {
                Console.Write(0);
                ReadyForZero = false;
            }
        }

        private void PrintEvens()
        {
            if (CurrentPrint % 2 == 0 && !ReadyForZero)
            {
                PrintNumber();
            }
        }

        private void PrintOdds()
        {
            if (CurrentPrint % 2 != 0 && !ReadyForZero)
            {
                PrintNumber();
            }
        }

        private void PrintNumber()
        {
            Console.Write(CurrentPrint);
            ReadyForZero = true;
            CurrentPrint++;
        }
    }

- Anthony September 10, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

package com.home.careercup;

import java.util.Deque;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/*
Thread ordering. There are 4 threads ( instead of three required by the problem ).
First thread keeps printing 0
Second thread prints 1, 3, 5, ..
Third thread prints 0
Last thread will print 2,4,6,..
The synchronization will interleave the output to get the needed sequence
There is a Queue and condition variables to signal the queue condition.

First thread will act when queue size =0, drops a token into the queue.
Signals that queue size =1

Second thread waits till queue size =1 and then prints and then drops another token
into the queue. Signals to others that size = 2

Third thread waits till queue size =2 and then prints and then drops another token
into the queue. Signals to others that size = 3

Last thread waits till queue size =3 and then prints and then drops another token
into the queue. But size is now 4 and the queue is drained. Signals to others that
the queue size = 0. The first thread can now do its printing again.

Cycle continues .. ??

It should be trivial to implement something similar with 3 threads instead of 4.
 */
public class ThreadOrdering {

    public static void main(String[] args) throws Exception {
        Lock master = new ReentrantLock(true);
        Condition c0 = master.newCondition(); // queue size =0
        Condition c1 = master.newCondition();// queue size= 1
        Condition c2 = master.newCondition();// queue size =2
        Condition c3 = master.newCondition(); // queue size =3

        new Thread(new Printer(0, 0, 0, master, c0, c1)).start();
        new Thread(new Printer(1, 2, 1, master, c1, c2)).start();
        new Thread(new Printer(0, 0, 2, master, c2, c3)).start();
        new Thread(new Printer(2, 2, 3, master, c3, c0)).start();

        /*
        prints
        0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 0 10 0 11 0 12 0 13 0 14 0 15 0
        16 0 17 0 18 0 19 0 20 0 21 0 22 0 23 0 24 0 25 0 26 0 27 0 28 0 29 0 30 0
        31 0 32 0 33 0 ..
         */

    }

    private static class Printer implements Runnable {
        int start;
        int inc;
        int current, size;
        Lock lock;
        Condition[] conditions;

        Printer(int start, int inc, int size, Lock lock, Condition... conditions) {
            this.start = start;
            this.inc = inc;
            current = start;
            this.lock = lock;
            Queue<Integer> q = Printer.q;
            this.size = size;
            this.conditions = conditions;
        }

        //shared across all printer threads
        static Deque<Integer> q = new LinkedList<>();

        @Override
        public void run() {
            while (true) {
                try {
                    lock.lock();
                    while (this.q.size() != size)
                        conditions[0].await();
                    synchronized (System.out) {
                        System.out.printf("%d ", current);
                        current += inc;
                    }
                    this.q.offer(1);
                    if (this.q.size() >= 4)
                        while (this.q.size() != 0)
                            this.q.remove();
                    conditions[1].signalAll();

                } catch (Exception e) {

                } finally {
                    lock.unlock();
                }

            }
        }


    }
}

- Makarand September 12, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

package goldmansach;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class PrintThreadSeries {

	public static class Counter {
		int count = 1;
		boolean even = false;

		public void increment() {
			try {
				wait();

				System.out.println(count);
				count++;

			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			even = true;
			notifyAll();
		}
	}

	Counter counter = new Counter();
	
	static int count = 1;
	static Lock lock = new ReentrantLock();
	public static class MyThread extends Thread {
		String name = "one";
		public boolean zero = true;
		public boolean even = false;

	

		@Override
		public void run() {
			while (count < 7) {
				lock.lock();
				if (this.name.equals("one") && zero ) {
					System.out.println(0);
					zero = false;
					
					this.name= !even ? "two" : "three";
				} else if (this.name.equals("two")) {
					System.out.println(count);
					count++;
					zero = true;
					even = true;
					this.name ="one";
				} else if(this.name.equals("three")){
					System.out.println(count);
					count++;
					even = false;
					zero = true;
					this.name ="one";
				}
				lock.unlock();
			}
		}
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		PrintThreadSeries.Counter c = new PrintThreadSeries.Counter();
		MyThread t1 = new MyThread();
		MyThread t2 = new MyThread();
		MyThread t3 = new MyThread();
		t1.start();
		t2.start();
		t3.start();
	}

}

- Siddhi October 01, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

package goldmansach;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class PrintThreadSeries {

	public static class Counter {
		int count = 1;
		boolean even = false;

		public void increment() {
			try {
				wait();

				System.out.println(count);
				count++;

			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			even = true;
			notifyAll();
		}
	}

	Counter counter = new Counter();
	
	static int count = 1;
	static Lock lock = new ReentrantLock();
	public static class MyThread extends Thread {
		String name = "one";
		public boolean zero = true;
		public boolean even = false;

	

		@Override
		public void run() {
			while (count < 7) {
				lock.lock();
				if (this.name.equals("one") && zero ) {
					System.out.println(0);
					zero = false;
					
					this.name= !even ? "two" : "three";
				} else if (this.name.equals("two")) {
					System.out.println(count);
					count++;
					zero = true;
					even = true;
					this.name ="one";
				} else if(this.name.equals("three")){
					System.out.println(count);
					count++;
					even = false;
					zero = true;
					this.name ="one";
				}
				lock.unlock();
			}
		}
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		PrintThreadSeries.Counter c = new PrintThreadSeries.Counter();
		MyThread t1 = new MyThread();
		MyThread t2 = new MyThread();
		MyThread t3 = new MyThread();
		t1.start();
		t2.start();
		t3.start();
	}

}

- Siddhi October 01, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class PrintSeries0102030405 {

public static void main(String[] args) throws Exception {
Print0 print0 = new Print0();
PrintEven even = new PrintEven(print0);
Thread thread1 = new Thread(print0);
Thread thread2 = new Thread(even);
thread1.start();
Thread.sleep(200);
thread2.start();
}

}

class Print0 implements Runnable {

@Override
public void run() {

synchronized (this) {
int even = 2;
while (even < 20) {
System.out.print(0);
try {
this.wait(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
even += 2;
}

}

}

}

class PrintEven implements Runnable {
Print0 print0;

PrintEven(Print0 print0) {
this.print0 = print0;
}

@Override
public void run() {
synchronized (print0) {
int even = 2;
while (even < 20) {
System.out.print(even);
try {
print0.wait(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
even += 2;
}
}
}

}

- Pk October 08, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class PrintSeries0102030405 {

public static void main(String[] args) throws Exception {
Print0 print0 = new Print0();
PrintEven even = new PrintEven(print0);
PrintOdd odd = new PrintOdd(print0);
Thread thread1 = new Thread(print0);
Thread thread2 = new Thread(even);
Thread thread3 = new Thread(odd);
thread1.start();
Thread.sleep(200);
thread3.start();
Thread.sleep(200);
thread2.start();
}

}

class Print0 implements Runnable {

@Override
public void run() {

synchronized (this) {
int even = 2;
while (even < 20) {
System.out.print(0);
try {
this.wait(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
even += 2;
}

}

}

}

class PrintOdd implements Runnable {
Print0 print0;

PrintOdd(Print0 print0) {
this.print0 = print0;
}

@Override
public void run() {
synchronized (print0) {
int odd = 1;
while (odd < 20) {
System.out.print(odd);
try {
print0.wait(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
odd += 2;
}
}
}

}

class PrintEven implements Runnable {
Print0 print0;

PrintEven(Print0 print0) {
this.print0 = print0;
}

@Override
public void run() {
synchronized (print0) {
int even = 2;
while (even < 20) {
System.out.print(even);
try {
print0.wait(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
even += 2;
}
}
}

}

- Pk October 08, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Below is the Simple C++11 solution

#include<iostream>
#include<thread>
#include<pthread.h>
using namespace std;

pthread_mutex_t lock;
int turn = 1;

void trythis(int id)
{
    static int count = 1;
    bool flag = true;
    while(flag) {
        pthread_mutex_lock(&lock);
        if(count == 7) {
            break;
            flag = false;
        }
        if(turn == 1) {
            if(id == 1) {
                cout<<"0";
                turn = (count % 2) == 0 ? 2 : 3;
            }
        } else if (turn == 2) {
            if(id == 2) {
                cout<<count;
                count++;
                turn = 1;
            }
        } else if( turn == 3) {
            if(id == 2) {
                cout<<count;
                count++;
                turn = 1;
            }
        }
        pthread_mutex_unlock(&lock);
    }
    return;
}

int main(void)
{
    int i = 0;
    int rc;
    int error;
    thread t1(trythis, 1);
    thread t2(trythis, 2);
    thread t3(trythis, 3);
    t1.join();
    t2.join();
    t3.join();
    return 0;
}

- DEEPAKKUSHWAH2302 October 08, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

pseudo code

semaphore sem1=1,sem2=0,sem3=0,sem4=0;

count =0;

thread1{

while(1){

wait (sem1);
print("0");
signal (sem3);

wait(sem2);
print(0);
signal(sem4);
}
}

thread2{
wait(sem3);
print(count++);
signal(sem2);
}

thread3{
wait(sem4);
print(count++);
signal(sem1);
}

- personal.dummy2016 October 12, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class Test010203 {
public static void main(String[] args) {
Object monitor = new Object();
Task task = new Task(monitor);

Thread t1=new Thread(task,"T1");
Thread t2=new Thread(task,"T2");
Thread t3=new Thread(task,"T3");

t1.start();
t2.start();
t3.start();

}
}

class Task implements Runnable {

private Object monitor = new Object();

private boolean firstTask=true;
private boolean secTask=false;
private boolean thridTask=false;

int count=1;
int i=0;


public Task(Object monitor){
this.monitor=monitor;
}

public void run(){
try {
while (true) {
synchronized (monitor) {
String tName = Thread.currentThread().getName();
if (firstTask && tName.equalsIgnoreCase("T1")) {
System.out.println(tName + ":" + "0");
if(i++ % 2 ==0) {
thridTask=true;
} else {
secTask=true;
}
firstTask=false;
monitor.notifyAll();
monitor.wait();
} else if (secTask && tName.equalsIgnoreCase("T2")) {
System.out.println(tName + ":" + i);
secTask=false;
firstTask=true;
monitor.notifyAll();
monitor.wait();
} else if (thridTask && tName.equalsIgnoreCase("T3")) {
System.out.println(tName + ":" + i);
thridTask=false;
firstTask=true;
monitor.notifyAll();
monitor.wait();
} else {
monitor.wait();
}
}
Thread.sleep(1000);
}
} catch (InterruptedException ie){
System.out.println("Thread interrupted ");
ie.printStackTrace();
} catch (Exception e) {
System.out.println("Other exception");
e.printStackTrace();
}
}

}

- Hemanth October 28, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class solution {

    static int state = 0;
    static int counter = 1;
    static volatile boolean runState = true;

    class ZeroOddEvenThreadLock implements Runnable {
        private String name;
        private Integer total;
        private ReentrantLock Lock;

        public ZeroOddEvenThreadLock(String name, Integer total, ReentrantLock Lock){
            this.name = name;
            this.total = total;
            this.Lock = Lock;
        }

        public void run(){
            while(runState) {
                if (counter > total) {
                    runState = false;
                    break;
                } else if ((state == 0 || state == 2) && name.equals("zero") ||
                        state == 1 && name.equals("odd") ||
                        state == 3 && name.equals("even")) {
                    Lock.lock();
                    try {
                        System.out.print((name.equals("zero") ? 0 : counter++));
                        state = (state + 1) % 4;
                    } finally {
                        Lock.unlock();
                    }
                }
            }
        }
    }

    public void ThreadQ1lock(){
	
        ExecutorService executor = Executors.newFixedThreadPool(3);
        ReentrantLock Lock = new ReentrantLock();

        int total = 6;

        Runnable zero = new ZeroOddEvenThreadLock("zero", total, Lock);
        Runnable odd = new ZeroOddEvenThreadLock("odd", total, Lock);
        Runnable even = new ZeroOddEvenThreadLock("even", total, Lock);

        executor.submit(zero);
        executor.submit(odd);
        executor.submit(even);

        stop(executor);
        System.out.println();
    }

    public static void main(String args[]){
        solution app = new solution();
        app.ThreadQ1lock();
    }
}

- dhruv November 02, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class Animation extends Thread {

static int a = 0;
static int odd = 1;
static int even = 2;
static int limit = 6;
static boolean x = false;

synchronized static void print() {

if (a == 0) {
System.out.print(a++);
if (x == false) {
a = 1;
} else {
a = 2;
}
} else if (a == 1) {
System.out.print(odd);
odd += 2;
a = 0;
x = true;
} else if (a == 2) {
System.out.print(even);
even += 2;
a = 0;
x = false;
}

}

public static void main(String[] args) {
Thread x = new Thread(new Thread() {
public void run() {
print();

}
});
Thread z = new Thread(new Thread() {

public void run() {
print();
}

});
while (true) {
if (odd == limit + 1) {
break;
}
print();
}
Animation l = new Animation();
l.start();
x.start();
z.start();

}

- Bahaa Samoudi November 25, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            OddEven.PrintOddEven();
            Console.ReadKey();
        }
    }

    public class OddEven
    {
        static SemaphoreSlim semaphoreSlim = new SemaphoreSlim(1, 1);
        static Thread Odd;
        static Thread Even;
        static Thread Zero;
        static LinkedList<int> Numbers = new LinkedList<int>();

        private static void PrintOdd()
        {
            while (Numbers.Count > 0)
            {
                semaphoreSlim.Wait();
                var a = Numbers.FirstOrDefault();
                if (a % 2 != 0)
                {
                    Console.WriteLine(a);
                    Numbers.RemoveFirst();
                }
                semaphoreSlim.Release();
            }
        }
        private static void PrintEven()
        {
            while (Numbers.Count > 0)
            {
                semaphoreSlim.Wait();
                var a = Numbers.FirstOrDefault();
                if (a % 2 == 0)
                {
                    Console.WriteLine(a);
                    Numbers.RemoveFirst();
                }
                semaphoreSlim.Release();
            }
        }

        private static void PrintZero()
        {
            while (Numbers.Count > 1)
            {
                semaphoreSlim.Wait();
                var a = Numbers.FirstOrDefault();
                if (a == 0)
                {
                    Console.WriteLine(a);
                    Numbers.RemoveFirst();
                }
                semaphoreSlim.Release();
            }
        }

        public static void PrintOddEven()
        {
            for (int i = 1; i <= 10; i++)
            {
                Numbers.AddLast(0);
                Numbers.AddLast(i);
            }

            Zero = new Thread(PrintZero);
            Odd = new Thread(PrintOdd);
            Even = new Thread(PrintEven);

            Zero.Name = "Zero";
            Odd.Name = "Odd";
            Even.Name = "Even";
            Zero.Start();
            Odd.Start();
            Even.Start();
            Odd.Join();
            Even.Join();
        }
    }
}

- GUL MD ERSHAD November 28, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

package problem.threading;

import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Print series 010203040506. Using multi-threading 1st thread will print only 0
 * 2nd thread will print only even numbers and 3rd thread print only odd
 * numbers.
 * 
 * @author ramsharma
 *
 */
public class ThreadSynch {

	private int st = 0;
	private static boolean flag;
	private final Object lock = new Object();
	private final CyclicBarrier cb = new CyclicBarrier(3);

	public static void main(String[] args) {
		ThreadSynch ths = new ThreadSynch();
		Thread printZero = new Thread(new ZeroThread(ths));
		Thread printOdd = new Thread(new OddThread(ths));
		Thread printEven = new Thread(new EvenThread(ths));

		// printZero.start();
		// printOdd.start();
		// printEven.start();

		ExecutorService exc = Executors.newFixedThreadPool(3);
		exc.submit(printZero);
		exc.submit(printOdd);
		exc.submit(printEven);

		exc.shutdown();
	}

	static class OddThread implements Runnable {

		private final ThreadSynch cb;

		public OddThread(ThreadSynch ths) {
			this.cb = ths;
		}

		@Override
		public void run() {
			for (int i = 1; i < 10; i = i + 2) {

				synchronized (cb) {

					while (cb.st != 1) {
						try {
							cb.wait();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}

					if (cb.st == 1) {
						System.out.print(i);
						// i += 2;
					}
					cb.st = 0;
					cb.notifyAll();
				}
				// cb.await();
			}
		}
	}

	static class EvenThread implements Runnable {

		private final ThreadSynch cb;

		public EvenThread(ThreadSynch ths) {
			this.cb = ths;
		}

		@Override
		public void run() {

			for (int i = 2; i < 10; i = i + 2) {

				synchronized (cb) {

					while (cb.st != 2) {
						try {
							cb.wait();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}

					if (cb.st == 2) {
						System.out.print(i);
						// i += 2;
					}
					cb.st = 0;
					cb.notifyAll();
				}
				// cb.await();
			}
		}
	}

	static class ZeroThread implements Runnable {

		private final ThreadSynch cb;

		public ZeroThread(ThreadSynch ths) {
			this.cb = ths;

		}

		@Override
		public void run() {
			for (int i = 0; i < 10; i++) {

				synchronized (cb) {
					while (cb.st != 0) {
						try {
							cb.wait();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}

					if (cb.st == 0) {
						System.out.print("0");
					}
					if (flag) {
						cb.st = 2;
						flag = false;
					}
					else {
						cb.st = 1;
						flag = true;
					}
					cb.notifyAll();
				}
			}
		}
	}
}

- shramdc November 29, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class MyThread implements Runnable {

    int num, in, orig;
    Object lock;
    static int turn = 0;

    MyThread(int num, int in, Object lock) {
        this.orig = num;
        this.num = num;
        this.in = in;
        this.lock = lock;
    }

    public void run() {
        synchronized (lock) {
            for (int i = 0; i < (orig==0?10:5); i++) {
                while (checkTurn() != orig) {
                    try {
                        lock.wait();
                    } catch (InterruptedException ex) {
                        System.out.println(ex.getMessage());
                    }
                }
                System.out.println(Thread.currentThread().getName() + " " + num);
                num += in;
                turn++;
                lock.notifyAll();
            }
        }
    }
    
    private int checkTurn() {
        if(turn%2!=0)
        {
            if(((turn+1)/2)%2==0)
                return 2;
            else
                return 1;
        }
        return 0;
    }

    public static void main(String[] args) {
        Object lock = new Object();
        Thread t1 = new Thread(new MyThread(0, 0, lock));
        Thread t3 = new Thread(new MyThread(1, 2, lock));
        Thread t2 = new Thread(new MyThread(2, 2, lock));

        t1.start();
        t3.start();
        t2.start();
    }
}

- Parth Shah December 12, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

/*
Print series 010203040506. Using multi-threading 1st thread will print only 0
2nd thread will print only even numbers and 3rd thread print only odd numbers.
*/
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>

int pos=0;
int count=1;
pthread_t tid[3];
pthread_mutex_t lock[3];

void* printEven(void *arg)
{
    pthread_mutex_lock(&lock[2]);
    pthread_mutex_lock(&lock[0]);
    while(pos < 12)
    {
        if((pos + 1)%4 == 0){
            printf("even %d\n", count);
            count++;
            pos++;
        }
        else
        {
           pthread_mutex_unlock(&lock[2]);
           pthread_mutex_unlock(&lock[0]);
        }
    }

    return NULL;

}
void* printOdd(void *arg)
{
    pthread_mutex_lock(&lock[1]);
    pthread_mutex_lock(&lock[2]);
    while(pos < 12)
    {
        if((pos - 1)%4 == 0){
            printf("Odd %d\n", count);
            count++;
            pos++;
        }
        else
        {
           pthread_mutex_unlock(&lock[1]);
           pthread_mutex_unlock(&lock[2]);
        }
    }

    return NULL;
}
void* printZero(void *arg)
{
    pthread_mutex_lock(&lock[0]);
    pthread_mutex_lock(&lock[1]);
    while(pos < 12)
    {
        if (pos%2 == 0){
            printf("Zero 0\n");
            pos++;
        }
        else
        {
           pthread_mutex_unlock(&lock[0]);
           pthread_mutex_unlock(&lock[1]);
        }
    }

    return NULL;

}
int main()
{
    int i;
    for(i=0;i<3;i++){
        if(pthread_mutex_init(&lock[i], NULL) != 0)
        {
            printf("Mutex creation failed\n");
            return 1;
        }
    }
    if( pthread_create(&tid[0], NULL, &printZero, NULL) !=0)
    {
        printf("Thread Creation failed!");
        return 1;
    }
    if(pthread_create(&tid[1], NULL, &printEven, NULL) !=0)
    {
        printf("Thread Creation failed!");
        return 1;
    }
    if(pthread_create(&tid[1], NULL, &printOdd, NULL) !=0)
    {
        printf("Thread Creation failed!");
        return 1;
    }
    for(i=0;i<3;i++)
        pthread_join(tid[i], NULL);
    for(i=0;i<3;i++)
        pthread_mutex_destroy(&lock[i]);

    return 0;
}

- RENJUASHOKAN January 07, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

int[] arr = { 0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6 };

Thread t0 = new Thread(p => Console.WriteLine($"Thread {Thread.CurrentThread.Name}: {string.Join(',', arr.Where(q => q == 0))}"));
t0.Name = "Zeros Thread";
t0.Start();

Thread tOdd = new Thread(p => Console.WriteLine($"Thread {Thread.CurrentThread.Name}: {string.Join(',', arr.Where(q => q % 2 != 0))}"));
tOdd.Name = "Odd Thread";
tOdd.Start();

Thread tEven = new Thread(p => Console.WriteLine($"Thread {Thread.CurrentThread.Name}: {string.Join(',', arr.Where(q => q % 2 == 0))}"));
tEven.Name = "Even Thread";
tEven.Start();

- BK February 11, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

int[] arr = { 0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6 };

            Thread t0 = new Thread(p => Console.WriteLine($"Thread {Thread.CurrentThread.Name}: {string.Join(',', arr.Where(q => q == 0))}"));
            t0.Name = "Zeros Thread";
            t0.Start();

            Thread tOdd = new Thread(p => Console.WriteLine($"Thread {Thread.CurrentThread.Name}: {string.Join(',', arr.Where(q => q % 2 != 0))}"));
            tOdd.Name = "Odd Thread";
            tOdd.Start();

            Thread tEven = new Thread(p => Console.WriteLine($"Thread {Thread.CurrentThread.Name}: {string.Join(',', arr.Where(q => q % 2 == 0))}"));
            tEven.Name = "Even Thread";
            tEven.Start();

- BK February 11, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

package javaStuff;

/**
 * Monitor based solution to alternate between 3 threads 
 * to print the sequence :  0 1 2 0 3 4 0 5 6..
 * 
 */
public class AlternateThreadDemo {
	public static void main(String[] args) {
		Monitor monitor = new Monitor(0); //start with thread-0's turn
		
		Thread t1 = new Thread(new MyJob(0, 0, monitor));
		Thread t2 = new Thread(new MyJob(1, 1, monitor));
		Thread t3 = new Thread(new MyJob(2, 2, monitor));
		
		t1.start();
		t2.start();
		t3.start();
	}
}

/**
 * Communicates which thread to run next. 
 * turn/prevTurn together determine this.
 *  
 * @author ayemmanu
 */
class Monitor{
	int turn;
	int prevTurn;
	public Monitor(int id){	this.turn = id;	}
}

class MyJob implements Runnable{
	Monitor monitor;
	int id;
	int val;
	
	public MyJob(int id, int val, Monitor monitor){
		this.id = id;
		this.val = val;
		this.monitor = monitor;
	}
	
	@Override
	public void run() {
		while(true){
			synchronized(monitor){
				
				while(monitor.turn != this.id) //Wait for my thread turn
					try {	monitor.wait();	} 
					catch (InterruptedException e) {}
				
				System.out.print(val + " ");
				
				if(val != 0) val += 2; //Value to be printed in next turn of this thread.
				
				//Logic to switch between threads - 0 1 0 2 0 1 0 2 ..
				//if cur is 0th thread: Next go to 2 if last visited=1. else go to 1 if last visited=2;
				//else: Next switch to 0'th thread if cur thread = 1 or 2
				if (monitor.turn == 0) { 
					if (monitor.prevTurn == 1)	monitor.turn = 2;
					else					monitor.turn = 1;
				} else { 
					monitor.prevTurn = monitor.turn;
					monitor.turn = 0;
				}
				
				try {	Thread.sleep(10);	} catch (InterruptedException e) {}
				
				monitor.notifyAll(); //Awake everyone
			}
		}
	}
}

- X February 12, 2018 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More