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

线程池用法(使用线程池创建线程)

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

线程池用法(使用线程池创建线程)

多线程-- 线程池

(1)自定义线程池(2)java自带的线程池

(1)自定义线程池

(1)为什么使用线程池
每一个线程的启动和结束都是比较消耗时间和占用资源的。使用线程池的过程中创建固定数量的线程,不用创建多余新的线程,而是循环使用那些已经存在的线程。

(2)自定义线程池设计思路
1-准备一个任务容器
2-一次性启动10个消费者线程
3-刚开始任务容器是空的,所以线程都wait在上面
4-直到一个外部线程往这个任务容器中扔了一个“任务”,就会有一个消费者线程被唤醒
5-这个消费者线程取出“任务”,并且执行这个任务,执行完毕后,继续等待下一次任务的到来
6-如果短时间内,有较多的任务加入,name就会有多个线程被唤醒,去执行这些任务

public class ThreadPool {
  
    // 线程池大小
    int threadPoolSize;
  
    // 任务容器
    linkedList tasks = new linkedList();
  
    // 试图消费任务的线程
  
    public ThreadPool() {
        threadPoolSize = 10;
  
        // 启动10个任务消费者线程
        synchronized (tasks) {
            for (int i = 0; i < threadPoolSize; i++) {
                new TaskConsumeThread("任务消费者线程 " + i).start();
            }
        }
    }
  
    public void add(Runnable r) {
        synchronized (tasks) {
            tasks.add(r);
            // 唤醒等待的任务消费者线程
            tasks.notifyAll();
        }
    }
  
    class TaskConsumeThread extends Thread {
        public TaskConsumeThread(String name) {
            super(name);
        }
  
        Runnable task;
  
        public void run() {
            System.out.println("启动: " + this.getName());
            while (true) {
                synchronized (tasks) {
                    while (tasks.isEmpty()) {
                        try {
                            tasks.wait();
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                    task = tasks.removeLast();
                    // 允许添加任务的线程可以继续添加任务
                    tasks.notifyAll();
  
                }
                System.out.println(this.getName() + " 获取到任务,并执行");
                task.run();
            }
        }
    }
  
}
public class TestThread {
       
    public static void main(String[] args) {
        ThreadPool pool = new ThreadPool();
  
        for (int i = 0; i < 5; i++) {
            Runnable task = new Runnable() {
                @Override
                public void run() {
                    //System.out.println("执行任务");
                    //任务可能是打印一句话
                    //可能是访问文件
                    //可能是做排序
                }
            };
             
            pool.add(task);
             
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
  
    }
           
}
(2)java自带的线程池

(1)线程池使用实例–使用java线程池实现穷举法破解密码

主要方法类

public class PassWordThreadpool {

    //第一步:把穷举法生成密码并且进行匹配的方法写好
    //如果匹配到密码了就停止遍历
    private boolean found = false;

    public synchronized void generatePwd(char[] guessPwd,String pwd, List pwdList) {
        generatePwd(guessPwd,0,pwd, pwdList);
    }

    public synchronized void generatePwd(char[] guessPwd,int index,String pwd, List pwdList) {
        //遍历数值和字母来生成密码
        if(found){
            return;
        }
        for (short i='0';i<'z';i++) {
            if(!Character.isLetterOrDigit(i)){
                continue;
            }
            char c = (char) i;
            guessPwd[index] = c;
            if(index==pwd.length()-1){
                //把三个字母的数组拼接成字符串
                String guessResult = new String(guessPwd);
                pwdList.add(guessResult);
                if(guessResult.equals(pwd)){
                    System.out.println("密码找到了,是:"+guessResult);
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    System.out.println("当前时间是:"+df.format(new Date()));
                    found = true;
                    return;
                }
            } else {
                generatePwd(guessPwd,index+1,pwd, pwdList);
            }
        }
    }
}

线程池使用

public class TestThreadpoolGuesspwd {
    public static void main(String[] args) throws InterruptedException {

        String pwd = randomPwd(3);
        System.out.println("生成的密码是:"+pwd);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("当前时间是:"+df.format(new Date()));
        List pwdList = new CopyOnWriteArrayList<>();
        PassWordThreadpool passWordThread = new PassWordThreadpool();

        ThreadPoolExecutor threadPool= new ThreadPoolExecutor(10, 15, 60, TimeUnit.SECONDS, new linkedBlockingQueue());

        threadPool.execute(() -> {
            char[] guessPwd = new char[pwd.length()];
            passWordThread.generatePwd(guessPwd,pwd, pwdList);
        });

    }

    public static String randomPwd(int length) {
        String pool = "";
        for (short i = '0'; i <= '9'; i++) {
            pool += (char) i;
        }
        for (short i = 'a'; i <= 'z'; i++) {
            pool += (char) i;
        }
        for (short i = 'A'; i <= 'Z'; i++) {
            pool += (char) i;
        }
        char cs[] = new char[length];
        for (int i = 0; i < cs.length; i++) {
            int index = (int) (Math.random() * pool.length());
            cs[i] = pool.charAt(index);
        }
        String result = new String(cs);
        return result;
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/775430.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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