簡體   English   中英

如何設置java.util.Timer的優先級

[英]How to set priority of java.util.Timer

如何在Java中設置計時器的線程優先級? 這是我在我正在處理的項目中找到的代碼,但我認為它不起作用:

public static Timer createNamedTimer(boolean isDaemon,
            final String threadName, final int priority) {
        Timer timer = new Timer(isDaemon);
        timer.schedule(new TimerTask() {
            public void run() {
                Thread.currentThread().setName("TimerThread: " + threadName);
                Thread.currentThread().setPriority(priority);
            }
        }, 0);
        return timer;
    }

定時器的AFAIK唯一可以更改優先級的方法就是您執行的方法。

如果需要更好的選擇,可以使用ThreadFactory創建線程並設置其優先級。

class SimpleThreadFactory implements ThreadFactory {
    private int threadPriority;
    public Thread newThread(Runnable r) {
     Thread t = new Thread(r);
     t.setPriority(threadPriority);
     return t;
   }
 }

然后,您可以將工廠傳遞給Java的Executors框架以執行所需的操作,恕我直言,這將是一種更好的方法。

為什么我說這將是更好的方法?

Timer類的JavaDoc提到ScheduledThreadPoolExecutor並指出,該類實際上是Timer/TimerTask組合的更通用的替代品

建議的解決方案不太適合重復多次的任務,因為在調用之間,共享同一線程的另一個任務可能已將優先級調整為其他任務。 因此,對於重復任務,您必須每次在執行時設置優先級。 沒有新的Executors框架就存在此潛在問題。

一種解決方案是創建一個包裝類,為您做准備工作以確保一致性。 例如:

AnyClass.java:

private static void exampleUsage()
{
   try { launchHighPriorityTask(() -> System.out.println("What a fancy task.")).join(); }
   catch (Throwable ignored) {}
}

private static Thread launchMaxPriorityTask(Runnable task)
{
  final Thread customThread = new Thread(new Task("MaxPriority", Thread.MAX_PRIORITY, task));
  customThread.start();
  return customThread;
}

Task.java:

public class Task implements Runnable
{
   private final String name;
   private final int priority;
   private final Runnable task;

   public Task(String name, int priority, Runnable task)
   {
      if (null == task) throw new NullPointerException("no task provided");
      this.name = name; this.priority = priority; this.task = task;
   }

   /**
    * run() is made final here to prevent any deriving classes 
    * accidentally ruining the expected behavior
    */
   @Override public final void run()
   {
      final Thread thread = Thread.currentThread();

      // cache the current state to restore settings and be polite
      final String prevName = thread.getName();
      final int prevPriority = thread.getPriority();

      // set our thread's config
      thread.setName(name);
      thread.setPriority(priority);

      try { task.run(); } catch (Throwable ignored) {}

      // restore previous thread config
      thread.setPriority(prevPriority);
      thread.setName(prevName);
   }
}

這自然是這種設置可以完成的極簡示例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM