关于并发编程的一个小demo

关于并发编程的一个小demo,第1张

关于并发编程的一个小demo 检测blockingqueue的功能
package com.concurrent;
import java.util.concurrent.BlockingQueue;

public class consumer extends Thread{
    BlockingQueue ssqueue;
    consumer(BlockingQueue bq){
        this.ssqueue = bq;
    }
    @Override
    public void run(){
        try {
            while(!Thread.currentThread().isInterrupted()) {
                    Integer take = ssqueue.take();
                    System.out.println("我成功消费了一个");
                    sleep(2000);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
package com.concurrent;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;


public class producer extends Thread {
    BlockingQueue ssqueue ;
    private int i = 0;
    producer(BlockingQueue bq){
        this.ssqueue = bq;
    }
    @Override
    public void run() {
        while(!Thread.currentThread().isInterrupted()) {
                try {
                    ssqueue.add(i++);
                    System.out.println("我成功生产了一个");
                    sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

        }
    }
}
package com.concurrent;

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


public class test {
    public static void main(String[] args) {
        BlockingQueue bq = new ArrayBlockingQueue(5);
        consumer con = new consumer(bq);
        producer p = new producer(bq);
        con.start();
        p.start();
    }
}

将在blockingqueue为满时抛出异常,但不会终止程序,只会终止producer线程,之后consumer线程继续消费,直到为0,然后阻塞队列进入阻塞状态

但是当我们使用线程池时将不会抛出异常:

package com.concurrent;

import java.util.concurrent.*;


public class test {
    public static void main(String[] args) {
        BlockingQueue bq = new ArrayBlockingQueue(5);
        consumer con = new consumer(bq);
        producer p = new producer(bq);
        ExecutorService executorService = Executors.newFixedThreadPool(20);
        executorService.submit(con);
        executorService.submit(p);
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5660148.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存