2

我正在处理线程任务,该任务需要为可调用线程分配优先级。

这是我的代码。

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分配具有优先级的线程。

4

1 回答 1

3

您可以使用自定义线程工厂实例化您的 Executor。

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());
于 2012-08-24T23:51:25.767 回答