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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值