package com.example.concurrency.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) public @interface Concurrent { String value() default ""; } package com.example.concurrency.tasks; import com.example.concurrency.annotations.Concurrent; @Concurrent public class MyTask implements Runnable { @Override public void run() { } } package com.example.concurrency.framework; import com.example.concurrency.annotations.Concurrent; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; public class AnnotationParser { public static List<Runnable> parseTasks(Class<?> clazz) { List<Runnable> tasks = new ArrayList<>(); Annotation annotation = clazz.getAnnotation(Concurrent.class); if (annotation != null) { tasks.add(createTask(clazz)); } Method[] methods = clazz.getDeclaredMethods(); for (Method method : methods) { annotation = method.getAnnotation(Concurrent.class); if (annotation != null) { tasks.add(createTask(clazz, method)); } } return tasks; } private static Runnable createTask(Class<?> clazz) { try { return (Runnable) clazz.getDeclaredConstructor().newInstance(); } catch (Exception e) { throw new RuntimeException("Failed to create task", e); } } private static Runnable createTask(Class<?> clazz, Method method) { try { return (Runnable) method.invoke(clazz.getDeclaredConstructor().newInstance()); } catch (Exception e) { throw new RuntimeException("Failed to create task", e); } } } package com.example.concurrency; import com.example.concurrency.framework.AnnotationParser; public class Main { public static void main(String[] args) { List<Runnable> tasks = AnnotationParser.parseTasks(ConcurrencyApp.class); ExecutorService executor = Executors.newFixedThreadPool(tasks.size()); for (Runnable task : tasks) { executor.submit(task); } executor.shutdown(); } }


上一篇:
下一篇:
切换中文