IBM Interview Question
Developer Program EngineersTeam: ISL
Country: India
Interview Type: In-Person
Seems like a question to wait - notify (in java or condvars in C)
public class HelloWordTwoThread {
public class ThreadRunner {
Object lock = new Object();
boolean printHello = true;
int counter = 5;
Thread helloPrinter = new Thread() {
@Override
public void run() {
while (counter > 0) {
synchronized (lock) {
while (!printHello) {
try {
lock.wait();
} catch (InterruptedException e) {
System.err.println("Interrupt Exteption!");
}
}
if (counter > 0) {
System.out.print("Hello");
}
printHello = false;
lock.notify();
}
}
}
};
Thread worldPrinter = new Thread() {
@Override
public void run() {
while (counter > 0) {
synchronized (lock) {
while (printHello) {
try {
lock.wait();
} catch (InterruptedException e) {
System.err.println("Interrupt Exteption!");
}
}
if (counter > 0) {
System.out.println(" World");
}
printHello = true;
counter --;
lock.notify();
}
}
}
};
public void writeHelloWorl() {
helloPrinter.start();
worldPrinter.start();
try {
helloPrinter.join();
worldPrinter.join();
}catch (InterruptedException e) {
System.err.println("Interrupeted while Joining!");
}
}
}
public static void main(String[] args) {
new HelloWordTwoThread().new ThreadRunner().writeHelloWorl();
}
}
Main
public class HelloWorld {
/**
* @param args
*/
public static void main(String[] args) {
PrintHelloWorld printHelloWorld = new PrintHelloWorld();
Thread helloThread = new Thread(new HelloThread(printHelloWorld));
helloThread.setName("Hello");
Thread worldThread = new Thread(new WorldThread(printHelloWorld));
worldThread.setName("World");
worldThread.start();
helloThread.start();
}
}
HelloThread : Calls method to print Hello
public class HelloThread implements Runnable {
PrintHelloWorld printHelloWorld = null;
public HelloThread(PrintHelloWorld printHelloWorld) {
this.printHelloWorld = printHelloWorld;
}
public void run() {
int count = 0;
while (count < 10) {
printHelloWorld.printHello();
count++;
}
}
}
WorldThread : Prints World
public class WorldThread implements Runnable {
PrintHelloWorld printHelloWorld = null;
public WorldThread(PrintHelloWorld printHelloWorld) {
this.printHelloWorld = printHelloWorld;
}
public void run() {
int count = 0;
while (count < 10) {
printHelloWorld.printWorld();
count++;
}
}
}
Synchronized Print Class
public class PrintHelloWorld {
int count = 0;
public synchronized void printHello() {
while (count == 1) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Hello");
count++;
notifyAll();
}
public synchronized void printWorld() {
while (count == 0) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("World");
count--;
notifyAll();
}
}
class Hello extends Thread {
public void run() {
System.out.print("Hello ");
Thread.yield();
}
}
class World extends Thread {
public void run() {
System.out.print("World \t");
}
}
public class twoThreadPrint {
public static void main(String[] args) throws InterruptedException {
for(int i = 0 ; i< 5; i++) {
new Thread(new Hello()).start();
new Thread(new World()).start();
Thread.sleep(10);
}
}
}
public class HelloWorldThreads implements Runnable
{
public static void main( String args[] )
{
Thread hello = new Thread(new HelloWorldThreads());
Thread world = new Thread(new HelloWorldThreads());
hello.setName( "Hello" );
hello.setPriority( 10 );
world.setName( "World" );
hello.start();
world.start();
}
public void run()
{
while(true)
{
synchronized (HelloWorldThreads.class )
{
System.out.println(Thread.currentThread().getName());
try
{
Thread.sleep( 1000 );
HelloWorldThreads.class.notifyAll();
HelloWorldThreads.class.wait();
}
catch ( InterruptedException e )
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
public class ccup {
static Integer flag = 0;
static int n = 5;
/**
* @param args
*/
public static void main(String[] args) {
new Thread() {
@Override
public void run() {
while (flag < n * 2) {
synchronized (flag) {
if (flag % 2 == 0) {
System.out.print("Hello ");
flag++;
} else {
try {
sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}.start();
new Thread() {
@Override
public void run() {
while (flag < n * 2) {
synchronized (flag) {
if (flag % 2 == 1) {
System.out.print("World ");
flag++;
} else {
try {
sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}.start();
}
}
package helloworldapp;
class mthread implements Runnable
{
boolean flag=false;
public void run()
{
int i=0;
while(i<6)
{
if(!flag)
{
synchronized(this)
{
flag=true;
System.out.print("hello");
}
}
else
{
synchronized(this)
{
flag=false;
System.out.println(" world");
}
}
i++;
}
}
}
public class helloprintworld {
public static void main(String args[])
{
mthread m = new mthread();
Thread t1 = new Thread(m);
Thread t2 = new Thread(m);
t1.start();
t2.start();
}
}
#include <iostream>
#include <stdlib.h>
#include <pthread.h>
using namespace std;
void *print_hello( void *ptr );
void *print_world( void *ptr );
static int flag = 0;
int main(int argc, char **argv) {
pthread_t thread1, thread2;
pthread_create( &thread1, NULL, print_hello, NULL);
pthread_create( &thread2, NULL, print_world, NULL);
pthread_join( thread2, NULL);
}
void *print_hello( void *ptr )
{
do
{
while(flag % 2 == 1){}
cout<<"Hello ";
flag++;
}while(flag<11);
}
void *print_world( void *ptr )
{
do
{
while(flag % 2 == 0){}
cout<<"World ";
flag++;
}while(flag<12);
}
public class df
{
public static void main(String []args)throws InterruptedException
{
df f=new df();
for(int i=1;i<=5;i++)
{
Thread t= new Thread(new Runnable() {
public void run() {
df fg=new df();
fg.vv();
}});
Thread t1= new Thread(new Runnable() {
public void run() {
df fg1=new df();
fg1.vv1();
}});
t.start();
t1.start();
t.join();
}
}
public synchronized void vv()
{
System.out.print("hello");
}
public synchronized void vv1()
{
System.out.print("world\n");
}}
//Sample code -
class PrintWord {
boolean m_state;
void printHello() {
System.out.print("Hello");
}
void printWorld() {
System.out.println("World");
}
void setState(boolean state) {
m_state = state;
}
boolean getState() {
return m_state;
}
}
class HelloThread extends Thread {
PrintWord printWord;
HelloThread(PrintWord value) {
printWord = value;
}
public void run() {
while (true) {
synchronized (printWord) {
if (!printWord.getState()) {
printWord.printHello();
printWord.setState(true);
printWord.notify();
} else {
try {
printWord.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
class WorldThread extends Thread {
PrintWord printWord;
WorldThread(PrintWord value) {
printWord = value;
}
public void run() {
while (true) {
synchronized (printWord) {
if (printWord.getState()) {
printWord.printWorld();
printWord.setState(false);
printWord.notify();
} else {
try {
printWord.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
public class HelloWorld {
public static void main(String[] args) {
PrintWord printWord = new PrintWord();
HelloThread helloThread = new HelloThread(printWord);
WorldThread worldThread = new WorldThread(printWord);
helloThread.start();
worldThread.start();
}
}
public static void main(String[] args) {
final ReentrantLock lock1 = new ReentrantLock();
final Condition helloCondition = lock1.newCondition();
final Condition worldCondition = lock1.newCondition();
final AtomicBoolean helloDone = new AtomicBoolean(false);
final AtomicBoolean worldDone = new AtomicBoolean(false);
Thread tjob1 = new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
try{
lock1.lock();
for (int i = 0 ; i < 4 ; i++) {
System.out.println("HELLO");
Thread.sleep(1000);
helloDone.set(true);
helloCondition.signalAll();
while(!worldDone.get()) {
worldCondition.await();
}
worldDone.set(false);
}
}
catch (Exception e){
}finally{
lock1.unlock();
}
}
});
Thread tjob2 = new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
try{
lock1.lock();
for (int i = 0 ; i < 4 ; i++) {
while(!helloDone.get()) {
helloCondition.await();
}
helloDone.set(false);
System.out.println("WORLD");
Thread.sleep(1000);
worldDone.set(true);
worldCondition.signalAll();
}
}
catch (Exception e){
}finally{
lock1.unlock();
}
}
});
tjob2.start();
tjob1.start();
}
#include <stdio.h>
#include <pthread.h>
pthread_mutex_t hello_lock, world_lock;
void printhello()
{
while(1) {
pthread_mutex_lock(&hello_lock);
printf("Hello ");
pthread_mutex_unlock(&world_lock);
}
}
void printworld()
{
while(1) {
pthread_mutex_lock(&world_lock);
printf("World ");
pthread_mutex_unlock(&hello_lock);
}
}
int main()
{
pthread_t helloThread, worldThread;
pthread_mutex_init(&hmutex, NULL);
pthread_mutex_init(&wmutex, NULL);
pthread_create(&helloThread,NULL,(void *)printhello,NULL);
pthread_create(&helloThread,NULL,(void *)printhello,NULL);
// these will never get excuted
pthread_join(helloThread);
pthread_join(worldThread);
return 0;
}
#include <stdio.h>
#include <pthread.h>
pthread_mutex_t hello_lock, world_lock;
void printhello()
{
while(1) {
pthread_mutex_lock(&hello_lock);
printf("Hello ");
pthread_mutex_unlock(&world_lock);
}
}
void printworld()
{
while(1) {
pthread_mutex_lock(&world_lock);
printf("World ");
pthread_mutex_unlock(&hello_lock);
}
}
int main()
{
pthread_t helloThread, worldThread;
pthread_mutex_init(&hmutex, NULL);
pthread_mutex_init(&wmutex, NULL);
pthread_create(&helloThread,NULL,(void *)printhello,NULL);
pthread_create(&helloThread,NULL,(void *)printhello,NULL);
// these will never get excuted
pthread_join(helloThread);
pthread_join(worldThread);
return 0;
}
static void Main()
{
Mutex m = new Mutex();
Thread t = new Thread(GO);
t.Start();
Thread t2 = new Thread(Go2);
t2.Start();
Thread.CurrentThread.Join();
Console.ReadKey();
}
private static void Go2(object obj)
{
int i = 0;
while (i < 5)
{
Console.WriteLine("Hello");
e.Set();
e2.WaitOne();
i++;
}
}
static AutoResetEvent e = new AutoResetEvent(false);//make initial state as signalled
static AutoResetEvent e2 = new AutoResetEvent(false);//make initial state as signalled
private static void GO(object obj)
{
int i=0;
while (i < 5)
{
e.WaitOne();
Console.WriteLine("world");
e2.Set();
i++;
}
}
static bool canprint = true;
static int ctr = 0;
static string val = "hello";
}
{{
static void Main()
{
Mutex m = new Mutex();
Thread t = new Thread(GO);
t.Start();
Thread t2 = new Thread(Go2);
t2.Start();
Thread.CurrentThread.Join();
Console.ReadKey();
}
private static void Go2(object obj)
{
int i = 0;
while (i < 5)
{
Console.WriteLine("Hello");
e.Set();
e2.WaitOne();
i++;
}
}
static AutoResetEvent e = new AutoResetEvent(false);//make initial state as signalled
static AutoResetEvent e2 = new AutoResetEvent(false);//make initial state as signalled
private static void GO(object obj)
{
int i=0;
while (i < 5)
{
e.WaitOne();
Console.WriteLine("world");
e2.Set();
i++;
}
}
static bool canprint = true;
static int ctr = 0;
static string val = "hello";
}
}}
static pthread_mutex_t lock;
static int thread_num = 0;
static int frases_count = 6;
void* thread_f_hello(void* data){
bool exit = false;
while(!exit)
{
pthread_mutex_lock(&lock);
if(frases_count == 0)
exit = true;
else
if(thread_num == 0){
printf("Hello ");
thread_num++;
}
pthread_mutex_unlock(&lock);
}
return NULL;
}
void* thread_f_world(void* data){
bool exit = false;
while(!exit){
pthread_mutex_lock(&lock);
if(frases_count == 0)
exit = true;
else
if(thread_num == 1){
printf("World!\n");
thread_num--;
frases_count--;
}
pthread_mutex_unlock(&lock);
}
return NULL;
}
int main(int argc, char** argv)
{
pthread_t tid[2];
pthread_create(&(tid[0]), NULL, &thread_f_hello, NULL);
pthread_create(&(tid[1]), NULL, &thread_f_world, NULL);
pthread_join(tid[0], NULL);
pthread_join(tid[1], NULL);
return 0;
}
package threadTest;
class Print {
public void hello() throws InterruptedException {
synchronized (this) {
int i = 0;
while (i < 3) {
notify();
System.out.print("hello ");
wait();
i++;
}
}
}
public void world() throws InterruptedException {
synchronized (this) {
int i = 0;
while (i < 3) {
notify();
System.out.print("World ");
wait();
i++;
}
}
}
}
public class Type6 {
static Print p = new Print();
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(new Runnable() {
public void run() {
try {
p.hello();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
try {
p.world();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
t1.start();
t2.start();
t1.join();
t2.join();
}
}
class IBMThread
{
public static void main(String[] args)
{
Thread1 t1=new Thread1();
Thread2 t2=new Thread2();
Thread th1=new Thread(t1);
Thread th2=new Thread(t2);
th1.start();
th2.start();
}
}
class Thread1 implements Runnable
{
public void run()
{
for(int i=1;i<4;i++)
{
System.out.print("Hello ");
try{
Thread.sleep(1000);
}catch(Exception e){}
}
}
}
class Thread2 implements Runnable
{
public void run()
{
for(int i=1;i<4;i++)
{
System.out.println("World");
try{
Thread.sleep(1000);
}catch(Exception e){}
}
}
}
#include<stdio.h>
#include<pthread.h>
void* print_msg(void *m)
{
char *cp=(char *)m;
int i;
for(i=0; i<5; i++)
{
printf("%s", m);
// fflush(stdout);
sleep(1);
}
return NULL;
}
int main()
{
pthread_t t1, t2;
pthread_create(&t1, NULL, print_msg, (void *)"Hello");
pthread_create(&t2, NULL, print_msg, (void* ) "world !\n");
pthread_join(t1, NULL);
pthread_join(t2, NULL);
return 0;
}
#include<stdio.h>
#include<pthread.h>
void* print_msg(void *m)
{
char *cp=(char *)m;
int i;
for(i=0; i<5; i++)
{
printf("%s", m);
// fflush(stdout);
sleep(1);
}
return NULL;
}
int main()
{
pthread_t t1, t2;
pthread_create(&t1, NULL, print_msg, (void *)"Hello");
pthread_create(&t2, NULL, print_msg, (void* ) "world !\n");
pthread_join(t1, NULL);
pthread_join(t2, NULL);
return 0;
}
#include<stdio.h>
#include<pthread.h>
void* print_msg(void *m)
{
char *cp=(char *)m;
int i;
for(i=0; i<5; i++)
{
printf("%s", m);
// fflush(stdout);
sleep(1);
}
return NULL;
}
int main()
{
pthread_t t1, t2;
pthread_create(&t1, NULL, print_msg, (void *)"Hello");
pthread_create(&t2, NULL, print_msg, (void* ) "world !\n");
pthread_join(t1, NULL);
pthread_join(t2, NULL);
return 0;
}
~
~
~
~
~
~
class Print
{
int count=0;
public synchronized void printHello() {
while (count == 1) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Hello");
count++;
notifyAll();
}
public synchronized void printWorld() {
while (count == 0) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("World");
count--;
notifyAll();
}
}
public class PrintHelloWorld extends Thread{
Print print=null;
public PrintHelloWorld(Print printHW) {
this.print = printHW;
}
public void run() {
int count = 0;
while (count < 5) {
if(Thread.currentThread().getName().equalsIgnoreCase("Hello"))
{
print.printHello();
}
else if(Thread.currentThread().getName().equalsIgnoreCase("World"))
{
print.printWorld();
}
count++;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Print printHW= new Print();
Thread helloThread = new Thread(new PrintHelloWorld(printHW));
helloThread.setName("Hello");
Thread worldThread = new Thread(new PrintHelloWorld(printHW));
worldThread.setName("World");
worldThread.start();
helloThread.start();
}
}
public class ThreadExamp {
public static void main(String[] args) {
A a = new A();
B b = new B();
a.start();
b.start();
for(int i=0;i<6;i++)
{
a.display();
try {
a.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
b.display();
try {
b.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class A extends Thread
{
public void run()
{
}
public void display()
{
System.out.println("Hello");
}
}
class B extends Thread
{
public void run()
{
}
public void display()
{
System.out.println("world");
}
}
- sandeep March 05, 2013