Timer and true principle TimerTask introduction of use &

In fact, it is a scheduler Timer is concerned, but it's just a TimerTask implements a class run method, and specific TimerTask need to achieve your own, such as this:

imer timer = new Timer();
timer.schedule(new TimerTask() {
        public void run() {
            System.out.println("abc");
        }
}, 200000 , 1000);

Here TimerTask a direct implementation (of course, you can achieve a plurality TimerTask, may be a plurality of TimerTask Timer Timer will be assigned to the plurality of scheduled, we will discuss later Timer scheduling mechanism implemented mechanism that is internal), then written in the run method, started after the 20s, once every second, of course, you operate multiple timerTask by a timer object is, in fact, timerTask itself does not make sense, just a collection of objects and timer operation, to achieve it there must be a corresponding run method to be called, he even do not need to achieve Runnable, because it tends to confuse the public, and why? It is to say the focus of this article.

When it comes to the principles timer, let's look at some common methods Timer inside:

 

public void schedule(TimerTask task, long delay)

This method is a scheduling Task, after delay (ms) after the start scheduling, scheduling only once.

public void schedule(TimerTask task, Date time)

Scheduling time on the specified time point time.

public void schedule(TimerTask task, long delay, long period)

This method is scheduling a task, scheduled to start after the delay (ms), after each time scheduling, wait a minimum period (ms) after the start scheduling.

public void schedule(TimerTask task, Date firstTime, long period)

And a method of similar, the only difference is the second parameter is passed the first scheduled time.

public void scheduleAtFixedRate(TimerTask task, long delay, long period)

Scheduling a task, scheduled to start after the delay (ms), and then after each period (ms) scheduling again, looks and methods: schedule is the same, it is not true, according to the source code you will see later, schedule in the calculation of the first performance time when using the current time (obtained before the task execution) + time slice, and scheduleAtFixedRate is by the time the current need to be performed (that is, the time should be performed calculations appear) + time slot, which was the actual running time , which is the theoretical point in time, for example: schedule time slice is 5s, then theoretically be scheduled in the time slot 15, 20, but if the result of the acquisition some CPU is not scheduled, if the wait for the first 8s the first time was only scheduled, then the schedule method calculated the next time should be the first 13s instead of the 10s, so that next time more likely to be less scheduled after 20s one or more times, and each time is to scheduleAtFixedRate the calculated theoretical next scheduled time required to sort, when the first scheduled 8s, it should be the first to calculate the 10s, so it from The current time is 2s, then the re-scheduling queue ordering, will be given priority scheduling, then missed scheduled to minimize the situation.

public void scheduleAtFixedRate(TimerTask task, Date firstTime,long period)

As above, the only difference is that the first time as a Date scheduled time, instead of a time slice the current time

 First look at the Timer constructor There are several ways:

1 constructor: constructor with no arguments, simply by a thread configured Tiemer name prefixed

public Timer() {
    this("Timer-" + serialNumber());
}

After passing whether the background thread, if set to a background thread, the main thread ends, automatic timer ends, without the use cancel to complete the end of the timer

Constructor 2: Incoming whether the background thread, a background thread if and only if at the end of the process, automatically written off.

public Timer(boolean isDaemon) {
    this("Timer-" + serialNumber(), isDaemon);
}

The other two constructors responsible for passing in the name and start the timer:

    public Timer(String name, boolean isDaemon) {
        thread.setName(name);
        thread.setDaemon(isDaemon);
        thread.start();
    }

There is a thread, the thread is clearly a thread is wrapped in the Timer class, we look at the definition of this thread is:

private TimerThread thread = new TimerThread(queue);

TimerThread part is defined:

class TimerThread extends Thread {

See here know, internal Timer wraps a thread, it used independent of external thread scheduling, and TimerThread is a default type, default is less than the reference, was Timer they are using.

In addition thread, there is a very important attribute mentioned above are:

private TaskQueue queue = new TaskQueue();

At the name is a queue, the queue which can first guess what it is, then I should probably be scheduled task bar

There is also a property is: threadReaper, it is the Object type, a rewrite of finalize methods it is time for garbage collection, recycling out the appropriate information, do the GC-covering, that is, when the timer thread for some the reason died, but not cancel, inside information needs to be emptied out of the queue, but we usually do not consider this approach, so we know what java to write this method is on the line.

TaskQueue very simple structure, an array, a plus size, a bit like ArrayList, it is not the length is 128, of course not, ArrayList can expansion, it can be, but it will be a memory copy, so a Timer is concerned, as long as the internal not more than 128 the number of task is not cause expansion; interior offers add (TimerTask), size (), getMin (), get (int), removeMin (), quickRemove (int), rescheduleMin (long newTime), isEmpty (), clear (), fixUp (), fixDown (), heapify ();

This probably means there's method:

add (TimerTaskt) to add a task

() Task queue length size

A task getMin () Gets the current sort after recent need to perform at index 1, 0 is the head of the queue without any operation.

get (inti) Gets the specified index data, including of course the subscript 0.

removeMin () to delete a task currently carried out recently, which is the first element that is normally scheduled task only once, after the execution, calling this method, you can TimerTask removed from the queue.

quickRmove (inti) Removes the specified element, generally not to call this method, this method only when the purge occurred in the Timer, and when the corresponding TimerTask cancel method is called when this method will be called, also is to cancel a TimerTask, then it will be removed from the queue (note that if the task is in the execution, or still in execution, although the queue is removed), there is this method not cancel the Timer instead the TimerTask cancel method, it is a scheduler, a single task, and finally noted that after the completion quickRmove, the last element of the queue is added to this position, so in this case will cause inconsistencies order problems, there behind covering methods.

rescheduleMin (long newTime) is re-set the task currently executed next execution time, and the new sort it to the appropriate position in the queue, and the call is behind said fixDown method.

For fixUp and fixDown method is concerned, the former is when a new task when the first element in the tail of the queue, and then look forward whether there are tasks performed even later than he, if any, will be two tasks in order to exchange. FixDown the contrary, After performing the first task, a need to add a time slice execution time obtained, whereby the sequence needs to be carried out later comparison task.

The last method is heapify, in fact, the latter half of the queue, all do a fixeDown operation, this operation is mainly to covering quickRemove method, when a large number of quickRmove, after the order has been disrupted, this time half of the region do a very simple sort can be.

We continue to return to Timer, there were two methods: cancel () method and purge () method, in fact, cancel method in terms of a cancellation, you will find in the test, if carried out once the timer on this method It will end out

When you do a cancel operation for many Task, this time by calling the purge method to achieve the recovery of cancel out these kind of space, already mentioned above, this time will result in out of order, so you need to call heapify method to complete the team order rearranged

Guess you like

Origin www.cnblogs.com/deityjian/p/11391493.html