1 //Multi-threaded communication2 //Multiple threads work on the same resource, but the tasks are different3 //wait for wake-up method:4 //wait (): Turns the thread into a frozen state and threads are stored in the thread pool;5 //notify (): Wakes a thread in a thread (arbitrary)6 //Notifyall (): Wakes all threads;7 /**************************************************************/8 //Create a resource class9 classResourceTen { One Private BooleanFlag =false; A PrivateString name; - PrivateString sex; - Public synchronized voidset (String name,string sex) the { - if(flag) - Try - { + This. Wait (); - } + Catch(interruptedexception e) A { at } - This. Name =name; - This. Sex =sex; - This. flag=true; - This. Notify (); - } in Public synchronized voidget () - { to if(! This. Flag) + Try - { the This. Wait (); * } $ Catch(interruptedexception e)Panax Notoginseng { - } theSystem.out.println (name+ "--" +sex); + This. flag=false; A This. Notify (); the } + } - //Create an input task class $ classInputImplementsRunnable $ { - Resource R; - Input (Resource R) the { - This. R =R;Wuyi } the Public voidRun () - { Wu intx = 0; - while(true) About { $ if(x==0) - { -R.set ("Beast", "male"); - } A Else + { theR.set ("MEINV", "NV"); - } $x= (x+1)%2; the } the } the } the //set up the output task class - classOutputImplementsRunnable in { the Resource R; the Output (Resource R) About { the This. R =R; the } the Public voidRun () + { - while(true) the {Bayi synchronized(R) the { the r.get (); - } - } the the } the } the - classIoDemo1 the { the Public Static voidMain (string[] args) the {94 //Create a Resource object theResource r =NewResource (); the //Create an input task object theInput in =NewInput (r);98 //set up an output task object AboutOutput out =NewOutput (r); - //Create a process for importing tasks101Thread T1 =NewThread (in);102 //process for setting up an output task103Thread t2 =NewThread (out);104 //Open Thread the T1.start ();106 T2.start ();107 }108}
A communication applet between threads __ (java_thread_inout.output)