标签:
1 /** 2 * 要求:假定有10个消费者去消费生产的产品, 产品要保证顺序被其他任意消费者消费,上一个消费完了下一个才能消费 3 * 4 * @author trfizeng 5 * 6 */ 7 public class SCThread { 8 public static void main(String[] args) { 9 System.out.println("begin:" + (System.currentTimeMillis()) / 1000); 10 for (int i = 0; i < 10; i++) {// 不能动 相当于生产者 11 final String input = i + "";// 不能动 12 String output = TestDao.doSome(input); 13 System.out.println(Thread.currentThread().getName() + ":" + output); 14 } 15 } 16 17 // 此类不能动 相当于消费者 18 static class TestDao { 19 public static String doSome(String input) { 20 try { 21 Thread.sleep(1000); 22 } catch (Exception e) { 23 e.printStackTrace(); 24 } 25 String output = input + ":" + (System.currentTimeMillis() / 1000); 26 return output; 27 } 28 } 29 }
解决方案:
1 import java.util.concurrent.ArrayBlockingQueue; 2 import java.util.concurrent.BlockingQueue; 3 import java.util.concurrent.locks.Lock; 4 import java.util.concurrent.locks.ReentrantLock; 5 6 /** 7 * 要求:假定有10个消费者去消费生产的产品, 产品要保证顺序被其他任意消费者消费,上一个消费完了下一个才能消费 8 * 9 * @author trfizeng 10 * 11 */ 12 public class SCThread { 13 public static void main(String[] args) { 14 final Lock lock = new ReentrantLock(); 15 final BlockingQueue<String> blockingQueue = new ArrayBlockingQueue<String>( 16 10); 17 System.out.println("begin:" + (System.currentTimeMillis()) / 1000); 18 for (int i = 0; i < 10; i++) {// 不能动 相当于生产者 19 final String input = i + "";// 不能动 20 /* 21 * String output = TestDao.doSome(input); 22 * System.out.println(Thread.currentThread().getName() + ":" + 23 * output); 24 */ 25 try { 26 blockingQueue.put(input); 27 } catch (InterruptedException e1) { 28 e1.printStackTrace(); 29 } 30 } 31 32 for (int i = 0; i < 10; i++) { 33 new Thread() { 34 @Override 35 public void run() { 36 lock.lock(); 37 String output; 38 try { 39 // synchronized (SCThread.class) { 40 output = TestDao.doSome(blockingQueue.take()); 41 System.out.println(Thread.currentThread().getName() 42 + ":" + output); 43 // } 44 } catch (InterruptedException e) { 45 e.printStackTrace(); 46 } finally { 47 lock.unlock(); 48 } 49 } 50 }.start(); 51 } 52 } 53 54 // 此类不能动 相当于消费者 55 static class TestDao { 56 public static String doSome(String input) { 57 try { 58 Thread.sleep(1000); 59 } catch (Exception e) { 60 e.printStackTrace(); 61 } 62 String output = input + ":" + (System.currentTimeMillis() / 1000); 63 return output; 64 } 65 } 66 }
begin:1420089616
Thread-0:0:1420089617
Thread-1:1:1420089618
Thread-3:2:1420089619
Thread-4:3:1420089620
Thread-2:4:1420089621
Thread-5:5:1420089622
Thread-7:6:1420089623
Thread-6:7:1420089624
Thread-8:8:1420089625
Thread-9:9:1420089626
标签:
原文地址:http://www.cnblogs.com/trfizeng/p/4307686.html