利用Syschronized和wait,notify实现线程安全的阻塞队列
1 class MQueue { 2 3 private List<String> list = new ArrayList<String>(); 4 5 private int maxSize; 6 7 private Object lock = new Object(); 8 9 public MQueue(int maxSize){ 10 this.maxSize=maxSize; 11 System.out.println("线程"+Thread.currentThread().getName()+"已初始化长度为"+this.maxSize+"的队列"); 12 } 13 14 public void put(String element){ 15 synchronized (lock) { 16 if(this.list.size()==this.maxSize){ 17 try { 18 System.out.println("线程"+Thread.currentThread().getName()+"当前队列已满put等待..."); 19 lock.wait(); 20 } catch (InterruptedException e) { 21 e.printStackTrace(); 22 } 23 } 24 this.list.add(element); 25 System.out.println("线程"+Thread.currentThread().getName()+"向队列中加入元素:"+element); 26 lock.notifyAll(); //通知可以取数据 27 } 28 } 29 30 public String take(){ 31 synchronized (lock) { 32 if(this.list.size()==0){ 33 try { 34 System.out.println("线程"+Thread.currentThread().getName()+"队列为空take等待..."); 35 lock.wait(); 36 } catch (InterruptedException e) { 37 e.printStackTrace(); 38 } 39 } 40 String result = list.get(0); 41 list.remove(0); 42 System.out.println("线程"+Thread.currentThread().getName()+"获取数据:"+result); 43 lock.notifyAll(); //通知可以加入数据 44 return result; 45 } 46 } 47 } 48 49 public class DemoThread20 { 50 public static void main(String[] args) { 51 final MQueue q = new MQueue(5); 52 53 new Thread(new Runnable() { 54 @Override 55 public void run() { 56 q.put("1"); 57 q.put("2"); 58 q.put("3"); 59 q.put("4"); 60 q.put("5"); 61 q.put("6"); 62 } 63 },"t1").start(); 64 65 new Thread(new Runnable() { 66 @Override 67 public void run() { 68 q.put("11"); 69 q.put("21"); 70 q.put("31"); 71 q.put("41"); 72 q.put("51"); 73 q.put("61"); 74 } 75 },"t2").start(); 76 77 new Thread(new Runnable() { 78 @Override 79 public void run() { 80 q.take(); 81 q.take(); 82 q.take(); 83 q.take(); 84 q.take(); 85 } 86 },"t3").start(); 87 88 new Thread(new Runnable() { 89 @Override 90 public void run() { 91 q.take(); 92 q.take(); 93 q.take(); 94 q.take(); 95 q.take(); 96 } 97 },"t4").start(); 98 } 99 }