Write java code to print "Hello how are you"
Thread1 should have "Hello"
Thread2 should have "how are you"
both the threads should start at the same time

Answer Posted / tathagata

class Callme
{
synchronized void call(String msg)
{
System.out.print( msg
+ " ");
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println
("Interrupted");
}

}
}
class Caller implements Runnable
{
String msg;
Callme target;
Thread t;
public Caller(Callme targ, String s)
{
target = targ;
msg = s;
t = new Thread(this);
t.start();
}
public void run()
{
target.call(msg);
}
}
class Synch
{
public static void main(String args[])
{
Callme target = new Callme();
Caller ob1 = new Caller
(target, "Hello");
Caller ob2 = new Caller
(target, "How are you");
// wait for threads to end
try
{
ob1.t.join();

ob2.t.join();
}
catch(InterruptedException e)
{
System.out.println
("Interrupted");
}
}
}


The above program will print Hello how are you with two
diff thread

Is This Answer Correct ?    17 Yes 3 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What are "methods" and "fields"?

765


What is static in java?

772


Which package is imported by default?

830


Why java is not 100% object-oriented?

1174


What are access specifiers in java ?

784


Does sprintf add a null terminator?

819


What is the difference between and ?

685


What is java regex?

730


What are the advantages of exception handling in java?

825


If we don’t want some of the fields not to serialize how to do that?

774


What is the use of jtable?

846


What is the purpose of a transient variable?

792


What are the various access specifiers in java?

744


How to convert string to byte array and vice versa?

777


When wait(), notify(), notifyall() methods are called does it releases the lock or holds the acquired lock?

750