重い処理をバックグラウンドスレッド実行させてみる
重い処理をTimeline上に書いてしまうと、処理中はGUIが止まってしまうことになります。
それを回避するためにServiceとTaskを用いる方法があります。
重い処理をTaskに書いて、バックグラウンド実行し、GUIで定期的にモニタリングするようなプログラムを作ってみました。
Taskのcall関数内がバックグラウンドで実行するプログラムです。
sleepを入れているが、入れなくてもよい。バックグラウンド実行中もGUI操作を阻害しません。
なかなかよいです。
require 'jrubyfx' @@count = 0 class XTask < Java::javafx::concurrent::Task def call loop do sleep(0.03) puts "background #{@@count}" @@count += 1 end end end class XService < Java::javafx::concurrent::Service def createTask puts "CreateTask" XTask.new end end class Hello < JRubyFX::Application def initialize puts "intialise" @service = XService.new @pos_x = 100 end def start(stage) @stage = stage with(stage,title: "sample",width: 100,height: 50) do layout_scene do group do label("hello", id: "v") end end show end @service.start play end def play handler = EventHandler.impl do |n, e| @stage['#v'].text = "hello #{@@count}" puts "handler" end time = Timeline.new time.cycle_count = :indefinite time.keyFrames << KeyFrame.new(1000.ms, handler) time.play end end Hello.launch
はじめ、Rubyのスレッドを使ってみたのですが、うまくいかず、今回の方法にしました。
なかなかJRubyFXの情報がなくて苦戦中。
今回はJRubyFXでServiceとTaskがていぎされていなかったので、JavaFXから直接読んでしまっています。
JRubyFXは素晴らしいと思いますが完成度がまだまだでちょっと残念。。