Experiments with ruby-processing (processing-2.2.1) and JRubyArt for processing-3.0

Friday 20 August 2010

Exploring Threads in JRuby

I was well impressed recently with some ruby-processing work by Preston Lee, in which he has created a multi-threaded starfield http://github.com/preston/Starfield (seemingly using ruby-native threads). That got me thinking about exploring the use of java threads in jruby and possibly ruby-processing. Here is some of my experimentation:-


require 'java' 

module JavaLang                    # create a namespace for java.lang
  include_package "java.lang"      # we don't want to clash with Ruby Thread?
end

class ThreadImpl
  include JavaLang::Runnable       # include interface as a 'module'
  
  attr_reader :runner   # instance variables
  
  def initialize
    @runner = JavaLang::Thread.current_thread # get access to main thread
    puts "...in thread #{JavaLang::Thread.current_thread.get_name}"
  end
  
  def run
    puts "...in thread #{JavaLang::Thread.current_thread.get_name}"
  end
  
end

begin
  thread0 = JavaLang::Thread.new(ThreadImpl.new).start
  thread1 = JavaLang::Thread.new(ThreadImpl.new).start
  thread2 = JavaLang::Thread.new(ThreadImpl.new).start
  thread3 = JavaLang::Thread.new(ThreadImpl.new).start
  thread4 = JavaLang::Thread.new(ThreadImpl.new).start
  thread5 = JavaLang::Thread.new(ThreadImpl.new).start
  thread6 = JavaLang::Thread.new(ThreadImpl.new).start
  thread7 = JavaLang::Thread.new(ThreadImpl.new).start
rescue 
  puts $!
end


# Output when run:-
#
#...in thread main
#...in thread main
#...in thread Thread-0
#...in thread main
#...in thread Thread-1
#...in thread main
#...in thread Thread-2
#...in thread main
#...in thread Thread-3
#...in thread main
#...in thread Thread-4
#...in thread main
#...in thread Thread-5
#...in thread main
#...in thread Thread-6
#...in thread Thread-7

No comments:

Post a Comment

Followers

About Me

My photo
I have developed JRubyArt and propane new versions of ruby-processing for JRuby-9.1.5.0 and processing-3.2.2