|
| 1 | +package concurrency; |
| 2 | + |
| 3 | +import java.util.Collections; |
| 4 | +import java.util.concurrent.ArrayBlockingQueue; |
| 5 | +import java.util.concurrent.BlockingQueue; |
| 6 | +import java.util.concurrent.atomic.AtomicInteger; |
| 7 | + |
| 8 | +public class BlockingQueueCommunication { |
| 9 | + |
| 10 | + /** |
| 11 | + * @param args |
| 12 | + */ |
| 13 | + public static void main(String[] args) { |
| 14 | + |
| 15 | + final Business business = new Business(); |
| 16 | + new Thread( |
| 17 | + new Runnable() { |
| 18 | + |
| 19 | + @Override |
| 20 | + public void run() { |
| 21 | + |
| 22 | + for(int i=1;i<=50;i++){ |
| 23 | + business.sub(i); |
| 24 | + } |
| 25 | + |
| 26 | + } |
| 27 | + } |
| 28 | + ).start(); |
| 29 | + |
| 30 | + for(int i=1;i<=50;i++){ |
| 31 | + business.main(i); |
| 32 | + } |
| 33 | + |
| 34 | + } |
| 35 | + |
| 36 | + static class Business { |
| 37 | + |
| 38 | + |
| 39 | + BlockingQueue<Integer> queue1 = new ArrayBlockingQueue<Integer>(1); |
| 40 | + BlockingQueue<Integer> queue2 = new ArrayBlockingQueue<Integer>(1); |
| 41 | + |
| 42 | + { |
| 43 | + Collections.synchronizedMap(null); |
| 44 | + try { |
| 45 | + System.out.println("xxxxxdfsdsafdsa"); |
| 46 | + queue2.put(1); |
| 47 | + } catch (InterruptedException e) { |
| 48 | + // TODO Auto-generated catch block |
| 49 | + e.printStackTrace(); |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + public void sub(int i){ |
| 54 | + try { |
| 55 | + queue1.put(1); |
| 56 | + } catch (InterruptedException e) { |
| 57 | + // TODO Auto-generated catch block |
| 58 | + e.printStackTrace(); |
| 59 | + } |
| 60 | + for(int j=1;j<=10;j++){ |
| 61 | + System.out.println("sub thread sequece of " + j + ",loop of " + i); |
| 62 | + } |
| 63 | + try { |
| 64 | + queue2.take(); |
| 65 | + } catch (InterruptedException e) { |
| 66 | + // TODO Auto-generated catch block |
| 67 | + e.printStackTrace(); |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + public void main(int i){ |
| 72 | + try { |
| 73 | + queue2.put(1); |
| 74 | + } catch (InterruptedException e1) { |
| 75 | + // TODO Auto-generated catch block |
| 76 | + e1.printStackTrace(); |
| 77 | + } |
| 78 | + for(int j=1;j<=100;j++){ |
| 79 | + System.out.println("main thread sequece of " + j + ",loop of " + i); |
| 80 | + } |
| 81 | + try { |
| 82 | + queue1.take(); |
| 83 | + } catch (InterruptedException e) { |
| 84 | + // TODO Auto-generated catch block |
| 85 | + e.printStackTrace(); |
| 86 | + } |
| 87 | + } |
| 88 | + } |
| 89 | + |
| 90 | +} |
0 commit comments