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
What is api data?
What is map java?
Is class is a data type?
What is the meaning of flag day?
How many bits is a 64 bit byte?
What is float in java?
What is difference between length and length() method in java ?
How does finally block differ from finalize() method?
What is difference between java and java ee?
Does google use java?
Can static method access instance variables ?
How many types of assembly languages are there?
What does %d do in java?
What is wrapper class example?
What are register variables what are the advantages?