Sunday, August 25, 2019

One Thread Print A And Other Thread Print B

Writing a program with 2 threads, one thread print A and other thread print B.
Ouput should be like  "ABABABA....."

package com.shubh.thread.example;

public class PrintABThread2Main {

 public static void main(String[] args) {

  Thread t1 = new PrintABThread2("A");
  Thread t2 = new PrintABThread2("B");
  t1.start();
  t2.start();
 }
}

class PrintABThread2 extends Thread {

 private volatile String inputString;
 private volatile String printString = null;
 static Object lockObject = new Object();

 public PrintABThread2(String inputString) {
  this.inputString = inputString;
 }

 @Override
 public void run() {
  while (true) {
   synchronized (lockObject) {
    if (printString == inputString) {
     try {
      lockObject.wait();
     } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
    }
    System.out.println(inputString);
    printString = inputString;

    lockObject.notifyAll();

   }
  }
 }
}
Output of above program.

A
B
A
B
A
B
A
B
A
B
A
B
Second Way todo same program:

package com.shubh.thread.example;

public class PrintABMain {

 public static void main(String[] args) {

  PrintAB printAB = new PrintAB();
  Thread t1 = new PrintABThread(printAB);
  Thread t2 = new PrintABThread(printAB);
  t1.start();
  t2.start();
 }
}


package com.shubh.thread.example;

public class PrintABThread extends Thread {

 private PrintAB printAB;

 public PrintABThread(PrintAB printAB) {
  this.printAB = printAB;
 }

 @Override
 public void run() {
  while (true) {
   synchronized (printAB) {
    if (printAB.getStr() == "B") {
     try {
      printAB.wait();
     } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
    }
    printAB.printB();
    printAB.notifyAll();

   }
   synchronized (printAB) {
    if (printAB.getStr() == "A") {
     try {
      printAB.wait();
     } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
    }
    printAB.printA();
    printAB.notifyAll();

   }
  }
 }

}

package com.shubh.thread.example;

public class PrintAB {
 private String str;

 public void printA() {
  System.out.println("A");
  setStr("A");
 }

 public void printB() {
  System.out.println("B");
  setStr("B");
 }

 public String getStr() {
  return str;
 }

 public void setStr(String str) {
  this.str = str;
 }
}

No comments:

Post a Comment