1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
| package com.jh.collection;
import java.util.Random; import java.util.TreeSet; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue;
public class CollectionTest {
public static void main(String args[]) throws InterruptedException { testTreeSet(); testQueue(); }
private static void testQueue() throws InterruptedException { BlockingQueue<String> blockingQueue = new LinkedBlockingQueue<String>(); ExecutorService executorService = Executors.newFixedThreadPool(5); executorService.submit(new ProduceApple(blockingQueue)); executorService.submit(new EatApple(blockingQueue)); }
static class ProduceApple implements Runnable { BlockingQueue<String> blockingQueue;
public ProduceApple(BlockingQueue<String> blockingQueue) { this.blockingQueue = blockingQueue; }
@Override public void run() { while (true) { Random random = new Random(); int randomInt = random.nextInt(10); String appleName = "apple" + randomInt; System.out.println("生产苹果 " + appleName); blockingQueue.add(appleName); try { Thread.sleep(randomInt * 1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }
static class EatApple implements Runnable { BlockingQueue<String> blockingQueue;
public EatApple(BlockingQueue<String> blockingQueue) { this.blockingQueue = blockingQueue; }
@Override public void run() { while (true) { try { String appleName = blockingQueue.take(); System.out.println("吃苹果 := " + appleName); } catch (InterruptedException e) { e.printStackTrace(); } } } }
public static void testTreeSet() { TreeSet<Integer> treeSet = new TreeSet<Integer>(); treeSet.add(5); treeSet.add(1); treeSet.add(3); System.out.println(treeSet.first()); System.out.println(treeSet.last()); }
}
|