Three threads communicate with each other thread 1 start thread 2 2 start 3 3 start 1

Source: Internet
Author: User
Tags static class

Package Cn.itcast.heima2;import Java.util.concurrent.atomic.atomicinteger;import Java.util.concurrent.locks.condition;import Java.util.concurrent.locks.lock;import Java.util.concurrent.locks.reentrantlock;public class Threeconditioncommunication {public static void main (string[] args) {final business business = new Business (), New Thread (new Runnable () {@Override public void run () {for (int i=1;i <=50;i++) {business.sub2 (i);}} }). Start (); New Thread (New Runnable () {@Override public void run () {for (int i=1;i<=50;i++) {business.sub3 (i)}}). Start (); for (int i=1;i<=50;i++) {business.main (i);}} Static class Business {lock lock = new Reentrantlock (); Condition condition1 = Lock.newcondition (); Condition condition2 = Lock.newcondition (); Condition Condition3 = Lock.newcondition (); private int shouldsub = 1; public void sub2 (int i) {lock.lock (), try{while (shouldsub! = 2) {try {condition2.await ()} catch (Exception e) {//TOD O auto-generated Catch block E.printstacKtrace (); }} for (int j=1;j<=10;j++) {System.out.println ("Sub2 thread sequence of" + j + ", loop of" + i);} Shouldsub = 3; Condition3.signal (); }finally{Lock.unlock ();}} public void sub3 (int i) {lock.lock (), try{while (shouldsub! = 3) {try {condition3.await ()} catch (Exception e) {//TOD O auto-generated Catch block E.printstacktrace (); }} for (int j=1;j<=20;j++) {System.out.println ("SUB3 thread sequence of" + j + ", loop of" + i);} Shouldsub = 1; Condition1.signal (); }finally{Lock.unlock ();}} public void Main (int i) {lock.lock (), try{while (shouldsub! = 1) {try {condition1.await ();} catch (Exception e) {//TOD O auto-generated Catch block E.printstacktrace (); }} for (int j=1;j<=100;j++) {System.out.println ("main thread sequence of" + j + ", loop of" + i);} Shouldsub = 2; Condition2.signal (); }finally{Lock.unlock ();}} }}

Three threads communicate with each other thread 1 start thread 2 2 start 3 3 start 1

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.