Chan implements Iterable<T> { @Override public Iterator<T> iterator() { if (Config.DEBUG_PRINT) { System.out.printf("iterator()\n"); } return new ChanIterator<>(this); } private  Chan(int depth); static Chan<T> create(int depth); void send(T data); T receive(); Result<T> receiveWithResult(); void close(); void close(T end); int length(); int capacity(); @Override Iterator<T> iterator();  }
@Test public void testIterator() { for (int depth : new int[] { 0, 10}) { { final Chan<Integer> ch1 = Chan.create(depth); TestUtil.asyncSleepAndSendIntegersAndClose(100, ch1, null, 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15); int count = 1; for (Integer i : ch1) { assertEquals((Integer)count, i); count++; } assertEquals(16, count); } { final Chan<Integer> ch1 = Chan.create(depth); TestUtil.asyncSleepAndSendIntegersAndClose(100, ch1, null, 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15); int count = 1; Iterator<Integer> iter = ch1.iterator(); while (iter.hasNext()) { Integer i = iter.next(); assertEquals((Integer)count, i); count++; } assertEquals(16, count); } { final Chan<Integer> ch1 = Chan.create(depth); final Chan<Integer> done = Chan.create(0); Thread th = new Thread(new Runnable() { @Override public void run() { int c = 0; for (Integer i : ch1) { c++; } done.send(c); } }); th.start(); ch1.send(0); ch1.send(1); th.interrupt(); assertEquals((Integer)2, done.receive()); } } }