Java - Interthread通信

Java - Interthread通信

如果你知道进程间通信,那么你很容易理解interthread通信。当您开发两个或多个线程交换一些信息的应用程序时,Interthread通信很重要。

原文地址: http://blogxinxiucan.sh1.newtouch.com/2017/07/16/Java-Interthread通信/

有三个简单的方法和一个小技巧,使线程通信成为可能。所有三种方法都列在下面 -

Sr.No.方法和说明
1public void wait() 导致当前线程等到另一个线程调用notify()
2public void notify() 唤醒正在等待对象监视器的单个线程。
3public void notifyAll() 唤醒所有在同一个对象上调用wait()的线程。

这些方法已被实现为Object中的最终方法,因此它们在所有类中都可用。所有这三种方法只能从同步上下文中调用。


这个例子显示了两个线程如何使用wait()notify()方法进行通信。您可以使用相同的概念创建一个复杂的系统。

class Chat {
   boolean flag = false;

   public synchronized void Question(String msg) {
      if (flag) {
         try {
            wait();
         }catch (InterruptedException e) {
            e.printStackTrace();
         }
      }
      System.out.println(msg);
      flag = true;
      notify();
   }

   public synchronized void Answer(String msg) {
      if (!flag) {
         try {
            wait();
         }catch (InterruptedException e) {
            e.printStackTrace();
         }
      }

      System.out.println(msg);
      flag = false;
      notify();
   }
}
class T1 implements Runnable {
   Chat m;
   String[] s1 = { "Hi", "How are you ?", "I am also doing fine!" };

   public T1(Chat m1) {
      this.m = m1;
      new Thread(this, "Question").start();
   }

   public void run() {
      for (int i = 0; i < s1.length; i++) {
         m.Question(s1[i]);
      }
   }
}

class T2 implements Runnable {
   Chat m;
   String[] s2 = { "Hi", "I am good, what about you?", "Great!" };

   public T2(Chat m2) {
      this.m = m2;
      new Thread(this, "Answer").start();
   }

   public void run() {
      for (int i = 0; i < s2.length; i++) {
         m.Answer(s2[i]);
      }
   }
}
public class TestThread {
   public static void main(String[] args) {
      Chat m = new Chat();
      new T1(m);
      new T2(m);
   }
}

当上述程序被执行并执行时,会产生以下结果 -

Hi
Hi
How are you ?
I am good, what about you?
I am also doing fine!
Great!

上一篇 :Java - 线程同步

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值