Tuesday, 27 March 2018

Simple Thread example to use synchronization.


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

Difference between final, finally and finalize()?

final :Final is a keyword. Final is used to apply restrictions on class, method and variable. Final class can't be inherited, final ...