1

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

2 回答 2

2

AFAIK for timer 更改优先级的唯一方法就是您的操作方式。

如果您需要更好的选择,您可以使用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

于 2013-09-11T11:33:50.977 回答
1

建议的解决方案可能不适用于重复多次的任务,因为在调用之间共享同一线程的另一个任务可能已将优先级调整为其他内容。因此,对于重复任务,您必须在每次执行时设置优先级。这个潜在的问题在没有新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;
}

任务.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);
   }
}

这自然是使用这种设置可以完成的极简示例。

于 2016-03-21T21:57:50.937 回答