Java线程工具类(基于Thread)

    xiaoxiao2022-07-04  119

    import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; //方法实现 public class App { public static void main(String[] args) throws InterruptedException, ExecutionException { Threads threadUtils = new Threads.ThreadBuilder().setThreadGroup("PAD").build(); threadUtils.setOperator(new Threads.operateThread() { @Override public void operatorBefore(Thread t) { System.out.println( "Excutor Before-------------------------------------------------->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>."); } @Override public void operatorAfter(Thread t) { System.out.println( "Excutor After-------------------------------------------------->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>."); } }); Runnable run = new Runnable() { @Override public void run() { for (int i = 0; i < 10; i++) { System.out.println("----------Currtent Thread------" + Thread.currentThread()); } } }; for (int i = 0; i < 10; i++) { threadUtils.excute(run); } } } //自己封装的工具类 class Threads { private operateThread operator; private ThreadGroup threadGroup; public Threads() { } public synchronized final ThreadGroup getThreadGroup() { return threadGroup; } public synchronized final void setThreadGroup(ThreadGroup threadGroup) { this.threadGroup = threadGroup; } public static class ThreadBuilder { private ThreadGroup Group; public ThreadBuilder setThreadGroup(String groupID) { Group = new ThreadGroup(groupID); return this; } public Threads build() { Threads threads = new Threads(); if (Group != null) { threads.setThreadGroup(Group); } return threads; } } @SuppressWarnings("unchecked") public <T, K> FutureTask<K> excute(T task) { FutureTask<K> futureTask = null; checkThreadGroup(); checkOperator(); Thread thread = null; if (task instanceof Runnable) { thread = new Thread(threadGroup, (Runnable) task); operator.operatorBefore(thread); thread.start(); operator.operatorAfter(thread); } else if (task instanceof Callable<?>) { futureTask = new FutureTask<K>((Callable<K>) task); thread = new Thread(threadGroup, futureTask); operator.operatorBefore(thread); thread.start(); operator.operatorAfter(thread); } return futureTask; } public static interface operateThread { public void operatorBefore(Thread t); public void operatorAfter(Thread t); } private void checkOperator() { if (operator == null) { operator = new operateThread() { @Override public void operatorBefore(Thread t) { } @Override public void operatorAfter(Thread t) { } }; } } private void checkThreadGroup() { if (threadGroup == null) { threadGroup = new ThreadGroup("defaultGroup"); } } public void setOperator(operateThread operator) { this.operator = operator; } }
    最新回复(0)