为可调用类型线程分配优先级

lawou6xi  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(339)

我正在处理线程任务,它需要为可调用线程分配优先级。
这是我的密码。

public void processURL(String[] synchronous, String[] asynchronous) {
    ExecutorService es = Executors.newFixedThreadPool(NTHREADS);
    for (int i = 0; i < asynchronous.length; i++) {
        es.execute(new TaskAsyn("Asynchronous Task: " + i, asynchronous[i],
                waiting));
    }

    List<Future<ToStore>> futures = new ArrayList<Future<ToStore>>();
    for (int i = 0; i < synchronous.length; i++) {
        Future<ToStore> future = es.submit(new TaskSynch(
                "synchronous Task: " + i, synchronous[i], waiting));
        futures.add(future);
    }

    for (Future<ToStore> future : futures) {
        try {
            ToStore s = future.get();
            // TODO
            System.out.println("Synchronous Task: " + s.getUrl()
                    + " has finished.");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

    System.out.println("here");
}

在可调用线程中执行同步以在将来获得结果。在可运行线程中执行的异步。
我也可以创建异步可调用线程;不是重点,所以我唯一的问题是 ExecuterService 被分配有优先权的线程。

nxagd54h

nxagd54h1#

可以用自定义线程工厂示例化执行器。

public class MyThreadFactory implements ThreadFactory {
   public Thread newThread(Runnable r) {
     Thread t =  new Thread(r);
     t.setPriority(Thread.MAX_PRIORITY); //Or whatever priority
     return t;
   }
 }

ExecutorService es = Executors.newFixedThreadPool(NTHREADS,new MyThreadFactory());

相关问题