Start three thread a,b,c, output 10 times in ABC order

Source: Internet
Author: User

package jun;import java.util.concurrent.executorservice;import java.util.concurrent.executors; import java.util.concurrent.locks.condition;import java.util.concurrent.locks.lock;import  java.util.concurrent.locks.reentrantlock;/** *  starts three thread a,b,c and outputs 10 times in ABC order  *  * @ author xiejunbo * */public class abc {private int cond = 0;/ /Control ABC output Private lock lock = new reentrantlock ();//Mutex to secure thread access through the lock of the JDK private  Condition condition = lock.newcondition ();//thread Collaboration Public static void main (String[]  args)  {abc abc = new abc (); Threada ta = abc.new threada (); THREADB&NBSP;TB&NBSP;=&NBSP;ABC.NEW&NBSP;THREADB (); THREADC&NBSP;TC&NBSP;=&NBSP;ABC.NEW&NBSP;THREADC (); Executorservice executor = executors.newfixedthreadpool (3);//execute for  through thread pool (int i =  0; i < 10; i++)  {executor.execute (TA); Executor.execute (TB); Executor.execute (TC);} Executor.shutdown ();} Class threada implements runnable {public void run () {lock.lock ();//Locking try { while  (True)  {if (cond % 3 == 0)  {system.out.print (cond +  "A  "); Cond++;condition.signalall (); break;} Else{try {condition.await ();}  catch  (interruptedexception e)  {e.printstacktrace ();}}}  finally {lock.unlock ();//Unlock}}}class threadb implements runnable{public void  run () {Lock.lock ();try {while  (True)  {if  (cond % 3 == 1)  { System.out.print (cond +  "b "); Cond++;condition.signalall (); break;}  else {try {condition.await ();}  catch  (interruptedexception e)  {e.printstacktrace ();}}}  finally {lock.unlock ();}}} class threadc implements runnable {public void&Nbsp;run () {lock.lock (); Try {while (True) {if (cond % 3 == 2) {System.out.println (cond  +  "c "); Cond++;condition.signalall (); break;} Else{try {condition.await ();}  catch  (interruptedexception e)  {e.printstacktrace ();}}}  finally {lock.unlock ();}}}


Start three thread a,b,c, output 10 times in ABC order

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.