简体   繁体   中英

How to set priority of java.util.Timer

How to set the Thread priority of a Timer in 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.

If you need a better option you can use the ThreadFactory for creating the threads and setting their priority.

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.

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

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.

One solution is to create a wrapper class that does prep work for you to ensure consistency. For example:

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);
   }
}

This is naturally a minimalist example of what can be accomplished with this sort of setup.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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