Discuss / Java / 线程池 schedule 2

线程池 schedule 2

Topic source

Junes_99994

#1 Created at ... [Delete] [Delete and Lock User]

import java.util.concurrent.*;

import java.util.*;

import java.text.SimpleDateFormat;

import java.util.Set;

public class Main {

    public static void main(String[] args) {

        // 创建一个固定大小的线程池:

        // ScheduledExecutorService pool = Executors.newScheduledThreadPool(4);

        ScheduledThreadPoolExecutor pool = new ScheduledThreadPoolExecutor(4);

        ScheduledFuture<?> future = pool.scheduleAtFixedRate(new MyTask(), 0,

                200, TimeUnit.MILLISECONDS);

        // System.out.println((pool.getQueue().element()));

        // System.out.println(Thread..getState() Runnable.);

        try {

            // pool.shutdown(); // Disable new tasks from being submitted

            if (!pool.awaitTermination(2, TimeUnit.SECONDS)) {

                cprint("time Delayed:" + -future.getDelay(TimeUnit.MILLISECONDS) + "ms");

                // https://www.educative.io/answers/what-is-the-futureisdone-method-in-java

                cprint("task state:" + future.isDone());

                Set<Thread> threadSet = Thread.getAllStackTraces().keySet();

                // threadset

                for (Thread t : threadSet) {

                    // Printing the thread status using getState()

                    if (t.getName().substring(0, 4).equals("pool")) {

                        cprint("Thread :" + t + ":"

                                + "Thread status : "

                                + t.getState());

                    }

                    try {

                        Thread.sleep(20);

                    } catch (InterruptedException e) {

                        cprint(e.toString());

                    }

                }

                pool.shutdownNow();//

                // pool.shutdown();// Wait a while for existing tasks to terminate

                // Wait a while for tasks to respond to being cancelled

                if (!pool.awaitTermination(2, TimeUnit.SECONDS)) {

                    cprint("Pool did not terminate");

                }

            }

        } catch (InterruptedException ie) {

            // (Re-)Cancel if current thread also interrupted

            pool.shutdownNow();

            // Preserve interrupt status

            Thread.currentThread().interrupt();

        }

    }

    private static void cprint(String s) {

        final String ANSI_RESET = "\u001B[0m";

        final String ANSI_RED = "\u001B[31m";

        final String ANSI_GREEN = "\u001B[32m";

        System.out.println(ANSI_GREEN + s + ANSI_RESET);

    }

}

class MyTask implements Runnable {

    static final SimpleDateFormat sdfDate = new SimpleDateFormat("HH:mm:ss.SSS");

    Date st = new Date();

    Date et = new Date();

    @Override

    public void run() {

        // System.out.println(Thread.currentThread().getState());

        String threadId = Thread.currentThread().getName();

        Date dt = new Date();

        System.out.println("interval:" + (dt.getTime() - st.getTime()) + "ms");

        st = new Date(dt.getTime());

        System.out.println(sdfDate.format(st) + ":" + "start task " + threadId);

        try {

            int delta = 100 + (int) (Math.random() * 200);

            Thread.sleep(delta);

            et = new Date();

            System.out.println(sdfDate.format(et) + ":" + "end task " + threadId);

            System.out.println("period:" + (et.getTime() - st.getTime()) + "ms\n");

            // if (delta > 250) {//exception

            // int x = 0;

            // System.out.println(5 / x);

            // }

            // if (delta > 200) {// error

            // m();

            // }

        } catch (InterruptedException e) {

            System.out.println(e.toString());

        }

        // catch (Exception e) {

        // System.out.println(e.toString());

        // }

    }

    private void m() {

        try {

            m();

        } catch (Exception e) {

            System.out.println(e.toString());

        }

    };

}

Junes_99994

#2 Created at ... [Delete] [Delete and Lock User]
a)   在FixedRate模式下,假设每秒触发,如果某次任务执行时间超过1秒,后续任务会不会并发执行?
         i.  Schedule任务超时结束,则后续任务立即执行以持续补时差,直到回归正常(时间->任务)一一对应的序列
b)   如果任务抛出了异常,后续任务是否继续执行?
         i.   任务抛出了异常,如果通过catch获取,则处理后继续执行;否则,线程将被迫停止并由RUNNABLE状态进入 WAITING 状态。
       ii.  任务抛出了错误,线程也将被迫停止

  • 1

Reply