package com.test.yuvagen.basic;
/* Simple Thread example to use synchronization
* Read
more:http://javainterviewprograms.blogspot.in/
* */
public class SendMessageThread {
public void
sendMessage(String msg) {
System.out.println("sending\t"
+ msg);
try
{
Thread.sleep(1000);
}
catch (Exception e) {
e.printStackTrace();
}
}
public static
void main(String args[]) {
SendMessageThread
smT = new SendMessageThread();
ThreadSend
th = new ThreadSend("Hi", smT);
ThreadSend
th2 = new ThreadSend("Bye", smT);
th.start();
th2.start();
try
{
th.join();
th2.join();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
class ThreadSend extends Thread {
private
String str;
private
Thread th;
SendMessageThread
sm;
ThreadSend(String
msg, SendMessageThread smObj) {
str
= msg;
sm
= smObj;
}
@Override
public void
run() {
synchronized
(sm) {
sm.sendMessage(str);
}
}
}
Output:
sending Hi
sending Bye
No comments:
Post a Comment