繁体   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