您现在的位置是:首页 >

()奥秘 Java线程通信源代码中的奥秘探究

火烧 2023-02-02 05:35:22 1033
Java线程通信源代码中的奥秘探究   Java线程通信在使用的时候需要我们不断学习 在学习的时候会有很多的问题存在 其实我们在源代码中就能发现其中的奥秘 因为ThreadNum和ThreadChar

Java线程通信源代码中的奥秘探究  

  Java线程通信在使用的时候需要我们不断学习 在学习的时候会有很多的问题存在 其实我们在源代码中就能发现其中的奥秘 因为ThreadNum和ThreadChar都有对Objecto的引用 所以你wait和notify的时候都应该同步 Java线程通信具体看如下

   public class Test {

   public static void main(String[] args){

   Object o=new Object();

   Thread n=new ThreadNum(o);

   Thread c=new ThreadChar(o);

   n start();

   c start();

   }

()奥秘 Java线程通信源代码中的奥秘探究

   }

   class ThreadNum extends Thread{

   Object o;

   public ThreadNum(Object o){

   this o=o;

   }

   public void run(){

   for(int i= ;i< ;i++){

   System out println(i);

   System out println(++i);

   try {

   synchronized (this) {

   this wait();

   }

   } catch (InterruptedException e) {}

   synchronized (this) {

  

   this notify();

   }

   }

   }

   }

   class ThreadChar extends Thread{

   Object o;

   public ThreadChar(Object o){

   this o=o;

   }

   public void run(){

   for(char a= A ;a<= Z ;a++){

   System out println(a);

   synchronized (this) {

  

   this notify();

   }

   try {

   synchronized (this) {

   this wait();

   }

   } catch (InterruptedException e) {}

   }

   }

   }

lishixinzhi/Article/program/Java/hx/201311/26955  
永远跟党走
  • 如果你觉得本站很棒,可以通过扫码支付打赏哦!

    • 微信收款码
    • 支付宝收款码