Interview Question
Country: United States
If the order of suits does not matter, a simple Barrier (CyclicBarrier in Java) should do it.
Otherwise, I would use a Binary Semaphore for each thread: Sd, Sh, Ss, and Sc. Sd is initialized open, and others are closed. run() of Dice would do Sd.P(), print, Sh.V(); run() of Heart would do Sh.P(), print, Ss.V(); etc. All loops run through A, 2, 3... K
{
package tree.utils;
class CardGame{
String str[] = {"A","1","2","3","4","5","6","7","8","9","10","Q","K"};
/*static int indx;
static int cnt;*/
static int i = -1;
public synchronized void print(String symbol)
{
if(symbol == "Dice")
i = i + 1;
System.out.println(str[i] + " " + symbol);
}
}
class card extends Thread{
CardGame cardGame = new CardGame();
String symbol;
//static int indx = -1;
public card(String sym)
{
this.symbol = sym;
}
public void run()
{
synchronized(cardGame)
{
for(int i=1;i<=13;i++)
{
cardGame.print(symbol);
try{
Thread.sleep(1000);
}catch(InterruptedException ie)
{
}
}
}
}
}
public class CardTest {
public static void main(String[] args) {
card c = new card("Dice");
card c1 = new card("Heart");
card c2 = new card("Spade");
card c3 = new card("Club");
c.start();
c1.start();
c2.start();
c3.start();
}
}
}
{
class CardThread extends Thread{
char symbol;
Game g;
public CardThread(char symbol,Game g)
{
this.symbol = symbol;
this.g = g;
}
public void run()
{
for(int i=1; i<=13; i++)
{
synchronized(g)
{
if((i>g.prevProcessedNumber) && (g.threadCount != 0) && (g.threadCount < 4))
{
try{
g.wait();
}catch(InterruptedException ie){
}
}
g.threadCount++;
g.number = i;
g.prevProcessedNumber = i;
System.out.println(symbol + " " +i);
if(g.threadCount == 4)
{
g.threadCount = 0;
g.notifyAll();
}
}
}
}
}
class Game {
public int prevProcessedNumber = 0;
public int threadCount = 0;
public int number = 1;
}
public class MainClass {
public static void main(String[] args) {
Game g = new Game();
new CardThread('D',g).start();
new CardThread('C',g).start();
new CardThread('H',g).start();
new CardThread('S',g).start();
}
}
}
package com.poc.thread.data;
public class Card extends Thread{
private String threadName;
private int pickNum;
private String number[] = {"A","1","2","3","4","5","6","7","8","9","10","Q","K"};
public Card(String threadName,int pickNum)
{
this.threadName=threadName;
this.pickNum=pickNum;
}
public void run(){
System.out.println("am here"+threadName+number[pickNum]);
}
}
package com.poc.thread.main;
import com.poc.thread.data.Card;
public class CardExecutor {
public static void main(String[] args) throws InterruptedException {
for(int i=0;i<=12;i++)
{
Card d1= new Card("Diamond",i);
d1.start();
d1.join();
Card s1= new Card("Spade",i);
s1.start();
s1.join();
Card c1= new Card("Club",i);
c1.start();
c1.join();
Card h1 = new Card("Heart",i);
h1.start();
h1.join();
}
}
}
I am just putting in the logic here( writing entire code without a single comment is irritating for others).
Start threads in reverse order. That is, Start thread 'Clubs', which starts thread 'Spade',which starts thread 'Hearts', which in turn starts thread 'Dice'. Each thread 'joins' for the thread that it started to finish and then prints its value 'A','B'....etc.
*join - is a java way of making sure that a thread waits for another thread to end.
thread1.join(thread2) - thread1 will wait for thread2 to complete and then resume its exceution.
mainThread()
{
Start ThreadClubs("A');
Start ThreadClubs("2');
}
ThreadClubs(param)
{
start ThradSpade(param);
ThradSpade.join();
print 'Clubs '+param
}
ThreadSpade(param)
{
Start ThreadHearts(param);
ThreadHearts.join()
print 'Spade '+param;
}
ThreadHearts(param)
{
Start ThreadDice(param);
ThreadDice.join();
print 'Hearts '+param;
}
ThreadDice(param)
{
print 'Dice '+param;
}
One correction -
mainThread()
{
Start ThreadClubs("A');
this.join(ThreadClubs); // To make sure that child threads of above and below line codes don't interleave.
Start ThreadClubs("2');
}
//This we can achieve by using single Thread only
class MyThread extends Thread
{
boolean dice = false,heart = true,spade = true,club = true;
int count =0;
public void run()
{
dice();
}
public synchronized void dice()
{
count = count +1;
if(!dice)
{
System.out.println("Dice" +count);
heart = false;
dice = true;
heart();
}
}
public synchronized void heart()
{
if(!heart)
{
System.out.println("Heart"+ count);
spade = false;
heart = true;
spade();
}
}
public synchronized void spade()
{
if(!spade)
{
System.out.println("Spade" + count);
club = false;
spade = true;
club();
}
}
public synchronized void club()
{
if(!club)
{
System.out.println("club" +count);
club = true;
if(count < 2)
{
dice = false;
dice();
}
}
}
}
public class ThreadSync {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MyThread t1 = new MyThread();
t1.start();
}
}
/**
*
*/
/**
* @author r7b
*/
public class Symbol
{
private final class SharedRunnable implements Runnable
{
private Object sharedLock = new Object();
private String nextThread = "DICE";
private String nextValue = "A";
private volatile int counter = 0;
@Override
public void run()
{
while( true )
{
synchronized( sharedLock )
{
if( Thread.currentThread().getName().equals( nextThread ) )
{
System.out.println( Thread.currentThread().getName() + " "+nextValue );
if( "DICE".equals( nextThread ) )
{
nextThread = "HEARTS";
}
else if( "HEARTS".equals( nextThread ) )
{
nextThread = "SPADE";
}
else if( "SPADE".equals( nextThread ) )
{
nextThread = "CLUBS";
}
else if( "CLUBS".equals( nextThread ) )
{
nextThread = "DICE";
nextValue = "2";
if(++counter == 2) {
sharedLock.notifyAll();
break;
}
}
sharedLock.notifyAll();
}
else
{
if(counter == 2)
break;
try
{
sharedLock.wait();
}
catch( InterruptedException e )
{
e.printStackTrace();
}
}
}
}
}
}
/**
* @param args
*/
public static void main( String[] args )
{
new Symbol().createThreads();
}
public void createThreads()
{
SharedRunnable sharedRunnable = new SharedRunnable();
Thread diceThread = new Thread( sharedRunnable, "DICE" );
Thread spadeThread = new Thread( sharedRunnable, "SPADE" );
Thread clubsThread = new Thread( sharedRunnable, "CLUBS" );
Thread heartsThread = new Thread( sharedRunnable, "HEARTS" );
diceThread.start();
spadeThread.start();
clubsThread.start();
heartsThread.start();
}
}
/**
* @author r7b
*/
public class Symbol
{
private final class SharedRunnable implements Runnable
{
private Object sharedLock = new Object();
private String nextThread = "DICE";
private String nextValue = "A";
private volatile int counter = 0;
@Override
public void run()
{
while( true )
{
synchronized( sharedLock )
{
if( Thread.currentThread().getName().equals( nextThread ) )
{
System.out.println( Thread.currentThread().getName() + " "+nextValue );
if( "DICE".equals( nextThread ) )
{
nextThread = "HEARTS";
}
else if( "HEARTS".equals( nextThread ) )
{
nextThread = "SPADE";
}
else if( "SPADE".equals( nextThread ) )
{
nextThread = "CLUBS";
}
else if( "CLUBS".equals( nextThread ) )
{
nextThread = "DICE";
nextValue = "2";
if(++counter == 2) {
sharedLock.notifyAll();
break;
}
}
sharedLock.notifyAll();
}
else
{
if(counter == 2)
break;
try
{
sharedLock.wait();
}
catch( InterruptedException e )
{
e.printStackTrace();
}
}
}
}
}
}
/**
* @param args
*/
public static void main( String[] args )
{
new Symbol().createThreads();
}
public void createThreads()
{
SharedRunnable sharedRunnable = new SharedRunnable();
Thread diceThread = new Thread( sharedRunnable, "DICE" );
Thread spadeThread = new Thread( sharedRunnable, "SPADE" );
Thread clubsThread = new Thread( sharedRunnable, "CLUBS" );
Thread heartsThread = new Thread( sharedRunnable, "HEARTS" );
diceThread.start();
spadeThread.start();
clubsThread.start();
heartsThread.start();
}
}
/**
* @author r7b
*/
public class Symbol
{
private final class SharedRunnable implements Runnable
{
private Object sharedLock = new Object();
private String nextThread = "DICE";
private String nextValue = "A";
private volatile int counter = 0;
@Override
public void run()
{
while( true )
{
synchronized( sharedLock )
{
if( Thread.currentThread().getName().equals( nextThread ) )
{
System.out.println( Thread.currentThread().getName() + " "+nextValue );
if( "DICE".equals( nextThread ) )
{
nextThread = "HEARTS";
}
else if( "HEARTS".equals( nextThread ) )
{
nextThread = "SPADE";
}
else if( "SPADE".equals( nextThread ) )
{
nextThread = "CLUBS";
}
else if( "CLUBS".equals( nextThread ) )
{
nextThread = "DICE";
nextValue = "2";
if(++counter == 2) {
sharedLock.notifyAll();
break;
}
}
sharedLock.notifyAll();
}
else
{
if(counter == 2)
break;
try
{
sharedLock.wait();
}
catch( InterruptedException e )
{
e.printStackTrace();
}
}
}
}
}
}
/**
* @param args
*/
public static void main( String[] args )
{
new Symbol().createThreads();
}
public void createThreads()
{
SharedRunnable sharedRunnable = new SharedRunnable();
Thread diceThread = new Thread( sharedRunnable, "DICE" );
Thread spadeThread = new Thread( sharedRunnable, "SPADE" );
Thread clubsThread = new Thread( sharedRunnable, "CLUBS" );
Thread heartsThread = new Thread( sharedRunnable, "HEARTS" );
diceThread.start();
spadeThread.start();
clubsThread.start();
heartsThread.start();
}
}
/**
* @author r7b
*/
public class Symbol
{
private final class SharedRunnable implements Runnable
{
private Object sharedLock = new Object();
private String nextThread = "DICE";
private String nextValue = "A";
private volatile int counter = 0;
@Override
public void run()
{
while( true )
{
synchronized( sharedLock )
{
if( Thread.currentThread().getName().equals( nextThread ) )
{
System.out.println( Thread.currentThread().getName() + " "+nextValue );
if( "DICE".equals( nextThread ) )
{
nextThread = "HEARTS";
}
else if( "HEARTS".equals( nextThread ) )
{
nextThread = "SPADE";
}
else if( "SPADE".equals( nextThread ) )
{
nextThread = "CLUBS";
}
else if( "CLUBS".equals( nextThread ) )
{
nextThread = "DICE";
nextValue = "2";
if(++counter == 2) {
sharedLock.notifyAll();
break;
}
}
sharedLock.notifyAll();
}
else
{
if(counter == 2)
break;
try
{
sharedLock.wait();
}
catch( InterruptedException e )
{
e.printStackTrace();
}
}
}
}
}
}
/**
* @param args
*/
public static void main( String[] args )
{
new Symbol().createThreads();
}
public void createThreads()
{
SharedRunnable sharedRunnable = new SharedRunnable();
Thread diceThread = new Thread( sharedRunnable, "DICE" );
Thread spadeThread = new Thread( sharedRunnable, "SPADE" );
Thread clubsThread = new Thread( sharedRunnable, "CLUBS" );
Thread heartsThread = new Thread( sharedRunnable, "HEARTS" );
diceThread.start();
spadeThread.start();
clubsThread.start();
heartsThread.start();
}
}
In C it could be done directly I guess
#include<pthread.h>
#include<stdio.h>
void* run_dice(void*);
void* run_spade(void*);
void* run_hearts(void*);
void* run_clubs(void*);
void* run_dice(void* args) {
char* ch = (char*)args;
printf("Dice %c\n",*ch);
}
void* run_spade(void* args) {
char* ch = (char*)args;
printf("Spade %c\n",*ch);
}
void* run_hearts(void* args) {
char* ch = (char*)args;
printf("Hearts %c\n",*ch);
}
void* run_clubs(void* args) {
char* ch = (char*)args;
printf("Clubs %c\n\n",*ch);
}
int main() {
pthread_t tids[4];
char arr[]= {'A','B','C','D'};
int count;
scanf("%d",&count);
for(int i=0; i<count; i++) {
char ch = arr[i];
for(int j=0; j<4; j++) {
if(j == 0)
pthread_create(&tids[j],NULL,run_dice,&ch);
else if(j == 1)
pthread_create(&tids[j],NULL,run_spade,&ch);
else if(j == 2)
pthread_create(&tids[j],NULL,run_hearts,&ch);
else
pthread_create(&tids[j],NULL,run_clubs,&ch);
pthread_join(tids[j],NULL);
}
}
return 0;
}
import java.lang.*;
- Anand Thakur November 07, 2012class Cards extends Thread
{
private String cardName="";
private String number[] = {"A","1","2","3","4","5","6","7","8","9","10","Q","K"};
private static int count=0;
private static int sD=0;
private static int sH=1;
private static int sS=1;
private static int sC=1;
private static Object obj=new Object();
Cards(String name){
cardName=name;
}
public void run(){
try{
while(true){
if(count == 12)
System.exit(0);
if(this.cardName=="Dice"){
if(sD == 0){
System.out.println("Dice"+" "+number[count]);
sH=0;
sD=1;
synchronized(obj){
obj.notifyAll();
}
}
while(sD == 1){
synchronized(obj){
obj.wait();
}
if(sD==0){
System.out.println("Dice" + " " + number[count]);
sH=0;
sD=1;
synchronized(obj){
obj.notifyAll();
}
}
}
}
if(this.cardName=="Hearts"){
if(sH == 0){
System.out.println("Hearts"+" "+number[count]);
sD=0;
sH=1;
count++;
if(count == 12)
System.exit(0);
synchronized(obj){
obj.notifyAll();
}
}
while(sH == 1){
synchronized(obj){
obj.wait();
}
if(sH==0){
System.out.println("Hearts" + " " + number[count]);
sD=0;
sH=1;
count++;
if(count == 12)
System.exit(0);
synchronized(obj){
obj.notifyAll();
}
}
}
}
}
}
catch(java.lang.InterruptedException e){}
}
}