Answer to Question #234517 in Java | JSP | JSF for Adib

Question #234517

implement a Java program to make a chat platform using synchronization between 3 threads.

similar code like below:

class Chat {
   boolean fl = false;
   public synchronized void Ques(String g) {
      if (fl) {
         try {
            wait();
         }catch (InterruptedException e) {
            e.printStackTrace();
         }
      }
      System.out.println(g);
      fl=true;
      notify();
   }
   public synchronized void Ans(String g) {
      if (!fl) {
         try {
            wait();
         }catch (InterruptedException e) {
            e.printStackTrace();
         }
      }
      System.out.println(g);
      fl=false;
      notify();
   }}
class T1 implements Runnable{
   Chat m;
   String[] s1={"Hi","How r u ?"};

   public T1(Chat m1) {
      this.m=m1;
      new Thread(this,"Ques").start();
   }
   public void run() {
      for (int i=0;i<s1.length;i++) {
         m.Ques(s1[i]);
      }}}
class T2 implements Runnable {
   Chat m;
   String[] s2={ "Hi","Great" };
   public T2(Chat m2) {
      this.m=m2;
      new Thread(this,"Ans").start();
   }
   public void run() {
      for (int i=0;i<s2.length;i++) {
         m.Ans(s2[i]);
      }}}
public class TestThread {
   public static void main(String[] args) {
      Chat m=new Chat();
      new T1(m);
      new T2(m);
   }}










1
Expert's answer
2021-09-07T16:30:45-0400
import java.util.Random;


public class ChickenEgg {
	public static int getTimeSleep() {
		final Random random = new Random();
		int tm = random.nextInt(1000);
		if (tm < 10)
			tm *= 100;
		else if (tm < 100)
			tm *= 10;
		return tm;
	}


	public static void main(String[] args) {
		Egg egg = new Egg();
		System.out.println("What came first, the chicken or the egg?");


		egg.start();
		for (int i = 0; i < 5; i++) {
			try {


				Thread.sleep(ChickenEgg.getTimeSleep());
				System.out.println("Chicken");
			} catch (InterruptedException e) {
			}
		}
		if (egg.isAlive()) {


			try {


				egg.join();
			} catch (InterruptedException e) {
			}


			System.out.println("Chicken came first !!!");
		} else {


			System.out.println("Egg came first!!!");
		}
		System.out.println("Contest over");
	}
}

class Egg extends Thread {
	@Override
	public void run() {
		for (int i = 0; i < 5; i++) {
			try {
				sleep(ChickenEgg.getTimeSleep());
				System.out.println("Egg");
			} catch (InterruptedException e) {
			}
		}
	}
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS