Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ssis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何设置java.util.Timer的优先级_Java - Fatal编程技术网

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

如何设置java.util.Timer的优先级,java,Java,如何在java中设置计时器的线程优先级?这是我在项目中发现的代码,我认为它不起作用: public static Timer createNamedTimer(boolean isDaemon, final String threadName, final int priority) { Timer timer = new Timer(isDaemon); timer.schedule(new TimerTask() {

如何在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;
    }

对于计时器来说,唯一可以改变优先级的方法就是你这样做

如果需要更好的选项,可以使用创建线程和设置其优先级

class SimpleThreadFactory implements ThreadFactory {
    private int threadPriority;
    public Thread newThread(Runnable r) {
     Thread t = new Thread(r);
     t.setPriority(threadPriority);
     return t;
   }
 }
然后,您可以将工厂传递给Java框架来做您想做的事情,这将是一种更好的方法

为什么我说这是一个更好的方法


Timer类的JavaDoc提到了
ScheduledThreadPoolExecutor
,并指出该类实际上是
Timer/TimerTask
组合的一个更通用的替代品

建议的解决方案不太可能适用于重复多次的任务,因为在调用之间,共享同一线程的另一个任务可能已将优先级调整为其他任务。因此,对于重复任务,必须在每次执行时设置优先级。新的
执行者
框架不存在或不存在此潜在问题

一种解决方案是创建一个包装器类,为您做准备工作以确保一致性。例如:

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

这自然是一个使用这种设置可以实现的最简单的示例。

这里的问题是ScheduleThreadPoolExecutor只为重复事件提供“scheduleAtFixedRate”,并且它与计时器的计划没有相同的行为。例如,如果您的应用程序被系统暂停,那么在唤醒时,它将弥补“突发”中丢失的所有CPU时间,而Java的计时器没有这个问题。