码迷,mamicode.com
首页 > 其他好文 > 详细

并发的集合类

时间:2017-05-14 14:58:25      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:tac   ati   print   集合类   队列   save   super   cheng   blog   

package duoxiancheng;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class TestQueue {

    public static void main(String[] args) {
        BlockingQueue<String> queue=new ArrayBlockingQueue<String>(10);
        new Save(queue).start();
        new Get(queue).start();
        new Get(queue).start();
    }

}
class Save extends Thread{
    BlockingQueue<String> queue;
    static Object obj="hello";
    static int i=0;
    public Save(BlockingQueue<String> queue) {
        super();
        this.queue = queue;
    }
    
public void run(){

    while(true){
        try {
            synchronized (obj) {
                queue.put("张飞"+i++);
            }
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

}
class Get extends Thread{
    BlockingQueue<String> queue;

    public Get(BlockingQueue<String> queue) {
        super();
        this.queue = queue;
    }
    
public void run(){
    int i=1;
    while(true){
        
        try {
            System.out.println("队列中的个数是"+queue.size());
            System.out.println(Thread.currentThread().getName()+":"+queue.take());
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
    
}

 

并发的集合类

标签:tac   ati   print   集合类   队列   save   super   cheng   blog   

原文地址:http://www.cnblogs.com/zyy1130/p/6852458.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!