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
How does finally block differ from finalize() method?
Is hashmap thread safe?
What is math exp in java?
What is a line separator in java?
Can we have more than one package statement in source file ?
What do you understand by copy constructor in java?
Is a class subclass of itself?
Can you declare an interface method static?
What is the meaning of course?
What is the similarity between dynamic binding and linking?
Is 0 an irrational number?
What does .equals do in java?
How the metacharacters are different from the ordinary characters?
What is a numeric digit?
Why we use multi threading instead of multiprocessing?