• java 线程池


    1. 线程池

    View Code
    package com;
    
    import java.util.concurrent.Executors;
    import java.util.concurrent.ThreadPoolExecutor;
    
    public class MutiThread extends Thread {
        private static int MaxTask = 3;
        private static int currTask = 0;
        private static ThreadPoolExecutor pool = (ThreadPoolExecutor) Executors
                .newFixedThreadPool(MaxTask);
    
        private static String[][] task = { { "a", "a" }, { "b", "b" },
                { "c", "c" }, { "d", "d" }, { "e", "e" }, { "f", "f" },
                { "g", "g" }, { "h", "h" }, { "i", "i" }, { "g", "g" },
                { "k", "k" }, { "l", "l" }, { "m", "m" }, { "n", "n" },
                { "o", "o" }, { "u", "u" }, { "p", "p" }, { "r", "r" },
                { "s", "s" }, { "t", "t" }, { "u", "u" }, { "v", "v" },
                { "w", "w" }, { "x", "x" }, { "y", "y" }, { "z", "z" } };
    
        public synchronized static void addTask() {
            if (currTask >= task.length) {
                pool.shutdown();
                return;
            }
            TaskThread tt = new TaskThread();
            tt.setTname(task[currTask][0]);
            pool.execute(tt);
            currTask++;
        }
    
        @Override
        public void run() {
            for (int i = 0; i < MaxTask + 3; i++) {
                addTask();
            }
        }
    
        public static void main(String[] args) {
            new MutiThread().start();
    
        }
    
    }

    2. 任务对象

    View Code
    package com;
    
    import java.util.Random;
    
    public class TaskThread extends Thread {
        private int count = 3;
        private String tname;
        private static final Random r = new Random(System.currentTimeMillis());
    
        public void setTname(String tname) {
            this.tname = tname;
        }
    
        @Override
        public void run() {
            while (count > 0) {
                try {
                    int i = sleepTime();
                    System.out.println(getName() + ":" + tname + ", sleep " + i
                            + "s");
                    Thread.sleep(i * 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                count--;
            }
            MutiThread.addTask();
        }
    
        public synchronized int sleepTime() {
            return (r.nextInt(10) + 1);
        }
    
        public static void main(String[] args) {
            new TaskThread().start();
        }
    }
  • 相关阅读:
    通达OA二次开发
    通达OA 工作流程 表单设计 高级应用
    PLSQL Develop PlugIn 之脚本自动匹配补全工具CnPlugin
    Oracle性能优化之SQL语句
    Linux重置root密码步骤
    ORA-03113:通信通道的文件结尾解决
    Bat脚本实现MySQL数据库SQL文件备份
    访问父级组件实例
    访问根实例
    插槽其它示例
  • 原文地址:https://www.cnblogs.com/liubin0509/p/2790682.html
Copyright © 2020-2023  润新知