栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

线程池(背一背)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

线程池(背一背)

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.concurrent.*;

class HelloWorld {
    static class Worker extends Thread {
        BlockingQueue queue = null;
        int id=0;
        public Worker(BlockingQueue queue, int id) {
            this.queue = queue;
            this.id=id;
        }

        public void run() {
                while (!Thread.currentThread().isInterrupted()) {
                    try {
                    Runnable runnable = queue.take();
                    System.out.println("线程" + id + "正在执行");
                    runnable.run();
            } catch(InterruptedException e){
                    e.printStackTrace();
                        System.out.println("线程结束");
                    break;


                }}



        }
    }

    static class mypool {
        private BlockingQueue queue = new linkedBlockingQueue();

        ArrayList arrayList = new ArrayList<>();

        public void excute(Runnable command) throws InterruptedException {
            queue.put(command);
            if (arrayList.size() < 3) {
                Worker x = new Worker(queue,arrayList.size());
                x.start();
                arrayList.add(x);
            }
        }
        public void shutdown()throws InterruptedException
        {
            for(Worker worker:arrayList)
            {
                worker.interrupt();
            }
            for(Worker worker:arrayList)
            {
                worker.join();
            }
        }
    }



    static class Command implements Runnable
    {     int num;
        public Command(int num)
        {
            this.num=num;
        }
        public void run()
        {
            System.out.println("线程"+num+"正在工作");
        }
    }

    public static void main(String[] args) throws InterruptedException{
        mypool o=new mypool();
        for(int i=0;i<100;i++)
        {
            o.excute(new Command(i));
        }
        try {
           Thread.sleep(1000);
        }catch(InterruptedException e)
        {
            e.printStackTrace();
        }
        o.shutdown();
        System.out.println("线程池已销毁");

    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/762596.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号