简体   繁体   English

如何设置java.util.Timer的优先级

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

How to set the Thread priority of a Timer in java? 如何在Java中设置计时器的线程优先级? This is the code I have found in the project that I am working on, and I do not think that it is working: 这是我在我正在处理的项目中找到的代码,但我认为它不起作用:

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 for timer the only way you can change priority is the way you are doing it. 定时器的AFAIK唯一可以更改优先级的方法就是您执行的方法。

If you need a better option you can use the ThreadFactory for creating the threads and setting their priority. 如果需要更好的选择,可以使用ThreadFactory创建线程并设置其优先级。

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

Then you can pass the factory to the Executors framework of Java for doing what you want, IMHO this will be a much better approach. 然后,您可以将工厂传递给Java的Executors框架以执行所需的操作,恕我直言,这将是一种更好的方法。

Why do I say it would be a better approach? 为什么我说这将是更好的方法?

The Timer class's JavaDoc mentions ScheduledThreadPoolExecutor and notes, that this class is effectively a more versatile replacement for the Timer/TimerTask combination Timer类的JavaDoc提到ScheduledThreadPoolExecutor并指出,该类实际上是Timer/TimerTask组合的更通用的替代品

The suggested solution won't likely work for tasks that are repeated more than once, because between invocations another task that shared the same thread may have adjusted the priority to something else. 建议的解决方案不太适合重复多次的任务,因为在调用之间,共享同一线程的另一个任务可能已将优先级调整为其他任务。 Therefore, for repeating tasks you must set the priority at execution time, every time. 因此,对于重复任务,您必须每次在执行时设置优先级。 This potential issue exists w/or w/o the new Executors framework. 没有新的Executors框架就存在此潜在问题。

One solution is to create a wrapper class that does prep work for you to ensure consistency. 一种解决方案是创建一个包装类,为您做准备工作以确保一致性。 For example: 例如:

AnyClass.java: 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: 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);
   }
}

This is naturally a minimalist example of what can be accomplished with this sort of setup. 这自然是这种设置可以完成的极简示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM