Java多线程之BlockingQueue(一)

来源:互联网 发布:atheros linux驱动 编辑:程序博客网 时间:2024/05/18 18:45

故名思义,BlockingQueue,翻译过来就是阻塞的队列,也是就是该队列的存储数据和取数据操作都是线程阻塞的。

这怎么理解呢?queue.put(1);该操作是往队列中存放数据,l而BlockingQueue queue = new ArrayBlockingQueue(1);定义成

只可存放一个数据,那么如果该队列中如果原来存放中数据,put操作就是阻塞的,会一直等到别的线程把queue中的数据取出来了,

此时的put操作才能成功。同理,Object obj = queue.take();是取操作,也是线程阻塞的。如果队列中没有数据,那么take操作会一直

等待,等待别的线程往queue中put了数据,take操作才能成功。

package three.day.thread;



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


public class BlockingQueueTest {
public static void main(String[] args) {
final BlockingQueue queue = new ArrayBlockingQueue(1);
for(int i=0;i<2;i++){
new Thread(){
public void run(){
while(true){
try {
Thread.sleep((long)(Math.random()*1000));
System.out.println(Thread.currentThread().getName() + "准备放数据!");
queue.put(1);
System.out.println(Thread.currentThread().getName() + "已经放了数据," +
" ,队列目前有" + queue.size() + "个数据");
} catch (InterruptedException e) {
e.printStackTrace();
}


}
}

}.start();
}

new Thread(){
public void run(){
while(true){
try {
//将此处的睡眠时间分别改为100和1000,观察运行结果
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName() + "准备取数据!");
Object obj = queue.take();
System.out.println(Thread.currentThread().getName() + "已经取走数据," + obj +
" ,队列目前有" + queue.size() + "个数据");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

}.start();
}

}







package three.day.thread;


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


public class BlockingQueueCondition {


public static void main(String[] args) {

ExecutorService service = Executors.newCachedThreadPool();
final Business3 business = new Business3();
service.execute(new Runnable(){
public void run() {
while(true){
try {
Thread.currentThread().sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
business.sub();
}
}

});
try {
while (true){
try {
Thread.currentThread().sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
business.main();
}
} finally{
service.shutdown();
}
}


}


class Business3{
BlockingQueue subQueue = new ArrayBlockingQueue(1);
BlockingQueue mainQueue = new ArrayBlockingQueue(1);


{
try {
subQueue.put(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

public void sub(){
try
{
mainQueue.take();
for(int i=0;i<5;i++){
System.out.println(Thread.currentThread().getName() + " : " + i);
}
subQueue.put(1);
}catch(Exception e){


}
}

public void main(){

try
{
subQueue.take();
for(int i=0;i<5;i++){
System.out.println(Thread.currentThread().getName() + " : " + i);
}
mainQueue.put(1);
}catch(Exception e){
}
}
}

原创粉丝点击