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

时间:2012-08-24 13:02:51

标签: java multithreading threadpool runnable callable

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

这是我的代码。

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

1 个答案:

答案 0 :(得分: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());