`
xieyj
  • 浏览: 99917 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

openjdk的周期线程

阅读更多

        openjdk中周期线程为WatcherThread,在

        jint Threads::create_vm(JavaVMInitArgs* args, bool* canTryAgain) {

               ............

               if (PeriodicTask::num_tasks() > 0) {
                        WatcherThread::start(); //启动周期线程
                }

               .............

        }

         看看WatcherThread构造函数

         WatcherThread::WatcherThread() : Thread() {
                 if (os::create_thread(this, os::watcher_thread)) {//此步仅创建线程,并不自动运行
                         _watcher_thread = this;

                         os::set_priority(this, MaxPriority);
                         if (!DisableStartThread) {
                                    os::start_thread(this); //运行刚创建的线程
                         }
                }
          }

          由前文《java.lang.Thread.start》可知,在start之后将运行WatcherThread::run方法。

          void WatcherThread::run() {

                    .........

                    while(!_should_terminate) {

                              const size_t time_to_wait = PeriodicTask::time_to_wait(); //计算下一个任务所需等待的最小时间
                              os::sleep(this, time_to_wait, false);

                              //上面的等待其实和linux操作系统的定时任务原理一样,只不过操作系统是根据更低层的时间节拍来计算。

                              .........

                              PeriodicTask::real_time_tick(time_to_wait);//在PeriodicTask中调用任务

                              //没有任务,退出,个人感觉没有任务等待应该更好,不知道为何这样设计

                              if (PeriodicTask::num_tasks() == 0) {
                                     _should_terminate = true;
                              }

                     }

          }

          void PeriodicTask::real_time_tick(size_t delay_time) {

                   ...........

                   for(int index = 0; index < _num_tasks; index++) {

                            _tasks[index]->execute_if_pending(delay_time); //执行任务

                   }

          }

         加入任务队列,是通过下面的方法

         void PeriodicTask::enroll() {
                  if (_num_tasks == PeriodicTask::max_tasks)
                  fatal("Overflow in PeriodicTask table");
                  _tasks[_num_tasks++] = this;
         }

1
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics