小例子:创建三个线程A,B,C, A线程循环10次,接着B线程再循环10次,然后C线程再循环10次,然后A线程又循环10次,如此循环往复50次。
代码如下:
class="java">public class ThreeThreadCommunication { 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.sub1(i); } } }).start(); 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(); } } class Business{ Lock lock = new ReentrantLock(); Condition condition1 = lock.newCondition(); Condition condition2 = lock.newCondition(); Condition condition3 = lock.newCondition(); private int flag = 1; public void sub1(int j){ lock.lock(); try{ while(flag != 1){ condition1.await(); } for(int i = 1;i <= 10;i++){ System.out.println("sub1 thread sequence of " + i + ",loop of " + j); } flag = 2; condition2.signal(); } catch (Exception e) { e.printStackTrace(); }finally{ lock.unlock(); } } public void sub2(int j){ lock.lock(); try{ while(flag != 2){ condition2.await(); } for(int i = 1; i <= 10; i++){ System.out.println("sub2 thread sequence of " + i + ",loop of " + j); } flag = 3; condition3.signal(); } catch (Exception e) { e.printStackTrace(); }finally{ lock.unlock(); } } public void sub3(int j){ lock.lock(); try{ while(flag != 3){ condition3.await(); } for (int i = 1; i <= 10; i++) { System.out.println("sub3 thread sequence of " + i + ",loop of " + j); } flag = 1; condition1.signal(); } catch (Exception e) { e.printStackTrace(); }finally{ lock.unlock(); } } }
?
?